Пример #1
0
        public async Task ExecuteAsync(ActionContext context, ResultBase result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            var response = context.HttpContext.Response;

            ResolveContentTypeAndEncoding(
                null,
                response.ContentType,
                DefaultContentType,
                out var resolvedContentType,
                out var resolvedContentTypeEncoding);
            response.ContentType = resolvedContentType;
            var jsonSettings = new JsonSerializerSettings
            {
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };

            var content = result.ToJson(jsonSettings);

            response.ContentLength     = resolvedContentTypeEncoding.GetByteCount(content);
            await using var textWriter =
                            _httpResponseStreamWriterFactory.CreateWriter(response.Body, resolvedContentTypeEncoding);
            await textWriter.WriteAsync(content);

            await textWriter.FlushAsync();
        }
Пример #2
0
        public INdjsonWriter CreateWriter(ActionContext context, IStatusCodeActionResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            HttpResponse response = context.HttpContext.Response;

            response.ContentType = CONTENT_TYPE;

            if (result.StatusCode != null)
            {
                response.StatusCode = result.StatusCode.Value;
            }

            DisableResponseBuffering(context.HttpContext);

            return(new NewtonsoftNdjsonWriter(_httpResponseStreamWriterFactory.CreateWriter(response.Body, Encoding.UTF8), _options.SerializerSettings, _jsonArrayPool));
        }
        /// <summary>
        /// Execute the <see cref="HtmlBuilderRendererResult{TModel}"/>
        /// </summary>
        /// <param name="context">The action context</param>
        /// <param name="result">The action result</param>
        public async Task ExecuteAsync(ActionContext context, HtmlBuilderRendererResult <TModel> result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            _logger.LogInformation(1, "Executing EightyViewResult<{0}>", typeof(TModel).Name);

            var response = context.HttpContext.Response;

            if (result.StatusCode != null)
            {
                response.StatusCode = (int)result.StatusCode.Value;
            }
            response.ContentType = "text/html; charset=utf-8";

            var htmlBuilder = result.View.GetHtmlBuilder(result.Model);

            using (var writer = _writerFactory.CreateWriter(response.Body, Encoding.UTF8))
            {
                htmlBuilder.Write(writer);
                await writer.FlushAsync();
            }
        }
        public PartialJsonResultExecutorTests()
        {
            Mock.Get(this.httpRequest)
            .SetupGet(httpRequest => httpRequest.Query)
            .Returns(this.queryCollection);

            Mock.Get(this.httpContext)
            .SetupGet(httpContext => httpContext.Request)
            .Returns(this.httpRequest);

            Mock.Get(this.httpContext)
            .SetupGet(httpContext => httpContext.Response)
            .Returns(this.httpResponse);

            Mock.Get(this.writerFactory)
            .Setup(writerFactory => writerFactory.CreateWriter(It.IsAny <Stream>(), It.IsAny <Encoding>()))
            .Returns(new StringWriter(this.body));

            Mock.Get(this.options)
            .SetupGet(options => options.Value)
            .Returns(this.partialJsonOptions);

            this.executor      = new PartialJsonResultExecutor(this.writerFactory, this.logger, this.options, Mock.Of <ArrayPool <char> >());
            this.actionContext = new ActionContext()
            {
                HttpContext = this.httpContext
            };
        }
        public INdjsonTextWriter CreateWriter(ActionContext context, NdjsonStreamResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            HttpResponse response = context.HttpContext.Response;

            ResponseContentTypeHelper.ResolveContentTypeAndEncoding(result.ContentType, response.ContentType, DEFAULT_CONTENT_TYPE, out var resolvedContentType, out var resolvedContentTypeEncoding);
            response.ContentType = resolvedContentType;

            if (result.StatusCode != null)
            {
                response.StatusCode = result.StatusCode.Value;
            }

            DisableResponseBuffering(context.HttpContext);

            return(new NdjsonTextWriter(_httpResponseStreamWriterFactory.CreateWriter(response.Body, resolvedContentTypeEncoding), _options.SerializerSettings, _jsonArrayPool));
        }
        public async Task ExecuteAsync(ActionContext context, EmailViewResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            var response = context.HttpContext.Response;

            if (result.StatusCode != null)
            {
                response.StatusCode = result.StatusCode.Value;
            }

            _emailViewResultExecuting(_logger, response.ContentType, null);

            var httpContext    = context.HttpContext;
            var requestFeature = httpContext.Features.Get <Microsoft.AspNetCore.Http.Features.IHttpRequestFeature>();
            var query          = httpContext.Request.Query;
            var format         = query["format"];

            using (var textWriter = _httpResponseStreamWriterFactory.CreateWriter(response.Body, Encoding.UTF8))
            {
                var contentType = await WriteEmailAsync(result.Email, textWriter, format);

                await textWriter.FlushAsync();

                httpContext.Response.ContentType = contentType;
            }
        }
Пример #7
0
        public async Task ExecuteAsync(ActionContext context, MyContentResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }
            var response = context.HttpContext.Response;

            //ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
            //    null,
            //    response.ContentType,
            //    DefaultContentType,
            //    out var resolvedContentType,
            //    out var resolvedContentTypeEncoding);

            response.ContentType = response.ContentType ?? DefaultContentType;
            var defaultContentTypeEncoding = MediaType.GetEncoding(response.ContentType);

            if (result.Content != null)
            {
                string content = JsonConvert.SerializeObject(result.Content);
                response.ContentLength = defaultContentTypeEncoding.GetByteCount(content);
                using (var textWriter = _httpResponseStreamWriterFactory.CreateWriter(response.Body, defaultContentTypeEncoding))
                {
                    await textWriter.WriteAsync(content);

                    await textWriter.FlushAsync();
                }
            }
        }
Пример #8
0
        public PartialJsonResultExecutorTests()
        {
            Mock.Get(this.httpContext)
            .SetupGet(httpContext => httpContext.Request)
            .Returns(this.httpRequest);

            Mock.Get(this.httpContext)
            .SetupGet(httpContext => httpContext.Response)
            .Returns(this.httpResponse);

            Mock.Get(this.writerFactory)
            .Setup(writerFactory => writerFactory.CreateWriter(It.IsAny <Stream>(), It.IsAny <Encoding>()))
            .Returns(new StringWriter(this.body));

            Mock.Get(this.optionsMvcPartialJsonOptions)
            .SetupGet(options => options.Value)
            .Returns(this.mvcPartialJsonOptions);

            Mock.Get(this.optionsMvcOptions)
            .SetupGet(optionsMvcOptions => optionsMvcOptions.Value)
            .Returns(this.mvcOptions);

#if ASPNETCORE2
            this.executor = new PartialJsonResultExecutor(this.writerFactory, this.logger, this.optionsMvcPartialJsonOptions, this.fieldsParser, Mock.Of <ArrayPool <char> >());
#else
            this.executor = new PartialJsonResultExecutor(this.writerFactory, this.logger, this.optionsMvcOptions, this.optionsMvcPartialJsonOptions, this.fieldsParser, Mock.Of <ArrayPool <char> >());
#endif
            this.actionContext = new ActionContext()
            {
                HttpContext = this.httpContext
            };
        }
Пример #9
0
        public async Task ExecuteAsync(ActionContext context, DeliverResult deliverResult, IComponent Component)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (deliverResult == null)
            {
                throw new ArgumentNullException(nameof(deliverResult));
            }

            var response = context.HttpContext.Response;

            ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
                DefaultContentType,
                response.ContentType,
                DefaultContentType,
                out var resolvedContentType,
                out var resolvedContentTypeEncoding);

            response.ContentType = resolvedContentType;

            if (deliverResult.StatusCode != null)
            {
                response.StatusCode = deliverResult.StatusCode.Value;
            }

            var serializerSettings = deliverResult.SerializerSettings ?? _options.SerializerSettings;


            DeliverResultExecuting(_logger, deliverResult.Model);

            deliverResult.JsonModel = Component.Render(deliverResult.Model);

            using (var writer = _writerFactory.CreateWriter(response.Body, resolvedContentTypeEncoding))
            {
                using (var jsonWriter = new JsonTextWriter(writer))
                {
                    jsonWriter.ArrayPool           = _charPool;
                    jsonWriter.CloseOutput         = false;
                    jsonWriter.AutoCompleteOnClose = false;

                    var jsonSerializer = JsonSerializer.Create(serializerSettings);
                    jsonSerializer.Serialize(jsonWriter, deliverResult.JsonModel);
                }

                // Perf: call FlushAsync to call WriteAsync on the stream with any content left in the TextWriter's
                // buffers. This is better than just letting dispose handle it (which would result in a synchronous write).
                await writer.FlushAsync();
            }
        }
        public virtual async Task ExecuteAsync(ActionContext context, ContentResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            var response = context.HttpContext.Response;

            string   resolvedContentType;
            Encoding resolvedContentTypeEncoding;

            ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
                result.ContentType,
                response.ContentType,
                DefaultContentType,
                out resolvedContentType,
                out resolvedContentTypeEncoding);

            response.ContentType = resolvedContentType;

            if (result.StatusCode != null)
            {
                response.StatusCode = result.StatusCode.Value;
            }

            _logger.ContentResultExecuting(resolvedContentType);

            if (result.Content != null)
            {
                response.ContentLength = resolvedContentTypeEncoding.GetByteCount(result.Content);

                using (var textWriter = _httpResponseStreamWriterFactory.CreateWriter(response.Body, resolvedContentTypeEncoding))
                {
                    await textWriter.WriteAsync(result.Content);

                    // Flushing the HttpResponseStreamWriter does not flush the underlying stream. This just flushes
                    // the buffered text in the writer.
                    // We do this rather than letting dispose handle it because dispose would call Write and we want
                    // to call WriteAsync.
                    await textWriter.FlushAsync();
                }
            }
        }
Пример #11
0
        public virtual async Task ExecuteAsync(ActionContext context, ContentResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            var response = context.HttpContext.Response;

            string   resolvedContentType;
            Encoding resolvedContentTypeEncoding;

            ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
                result.ContentType,
                response.ContentType,
                DefaultContentType,
                out resolvedContentType,
                out resolvedContentTypeEncoding);

            response.ContentType = resolvedContentType;

            if (result.StatusCode != null)
            {
                response.StatusCode = result.StatusCode.Value;
            }

            if (result.Content != null)
            {
                response.ContentLength = resolvedContentTypeEncoding.GetByteCount(result.Content);

                using (var textWriter = _httpResponseStreamWriterFactory.CreateWriter(response.Body, resolvedContentTypeEncoding))
                {
                    await textWriter.WriteAsync(result.Content);

                    await textWriter.FlushAsync();
                }
            }
        }
Пример #12
0
        public async Task ExecuteAsync(ActionContext context, MyJsonResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            var response = context.HttpContext.Response;

            //ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
            //    null,
            //    response.ContentType,
            //    DefaultContentType,
            //    out var resolvedContentType,
            //    out var resolvedContentTypeEncoding);

            response.ContentType = response.ContentType ?? DefaultContentType;
            var defaultContentTypeEncoding = MediaType.GetEncoding(response.ContentType);

            var serializerSettings = _options.SerializerSettings;

            using (var writer = _writerFactory.CreateWriter(response.Body, defaultContentTypeEncoding))
            {
                using (var jsonWriter = new JsonTextWriter(writer))
                {
                    jsonWriter.ArrayPool           = _charPool;
                    jsonWriter.CloseOutput         = false;
                    jsonWriter.AutoCompleteOnClose = false;

                    var jsonSerializer = JsonSerializer.Create(serializerSettings);
                    jsonSerializer.Serialize(jsonWriter, result.Value);
                }

                await writer.FlushAsync();
            }
        }
Пример #13
0
        /// <summary>
        /// Execute the <see cref="HtmlResult"/>
        /// </summary>
        /// <param name="context">The action context</param>
        /// <param name="result">The action result</param>
        public async Task ExecuteAsync(ActionContext context, HtmlResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            _logger.LogInformation(1, "Executing HtmlResult");

            var response = context.HttpContext.Response;

            if (result.StatusCode != null)
            {
                response.StatusCode = (int)result.StatusCode.Value;
            }
            response.ContentType = "text/html; charset=utf-8";

            using (var writer = _writerFactory.CreateWriter(response.Body, Encoding.UTF8))
            {
                if (result.RenderAsync)
                {
                    await result.Html.WriteAsync(writer);

                    await writer.FlushAsync();
                }
                else
                {
                    result.Html.Write(writer);
                    await writer.FlushAsync();
                }
            }
        }
Пример #14
0
    public virtual async Task ExecuteAsync(ActionContext context, ViewComponentResult result)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (result == null)
        {
            throw new ArgumentNullException(nameof(result));
        }

        var response = context.HttpContext.Response;

        var viewData = result.ViewData;

        if (viewData == null)
        {
            viewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
        }

        var tempData = result.TempData;

        if (tempData == null)
        {
            tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
        }

        ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
            result.ContentType,
            response.ContentType,
            (ViewExecutor.DefaultContentType, Encoding.UTF8),
            MediaType.GetEncoding,
            out var resolvedContentType,
            out var resolvedContentTypeEncoding);

        response.ContentType = resolvedContentType;

        if (result.StatusCode != null)
        {
            response.StatusCode = result.StatusCode.Value;
        }

        await using var writer = _writerFactory.CreateWriter(response.Body, resolvedContentTypeEncoding);
        var viewContext = new ViewContext(
            context,
            NullView.Instance,
            viewData,
            tempData,
            writer,
            _htmlHelperOptions);

        OnExecuting(viewContext);

        // IViewComponentHelper is stateful, we want to make sure to retrieve it every time we need it.
        var viewComponentHelper = context.HttpContext.RequestServices.GetRequiredService <IViewComponentHelper>();

        (viewComponentHelper as IViewContextAware)?.Contextualize(viewContext);
        var viewComponentResult = await GetViewComponentResult(viewComponentHelper, _logger, result);

        if (viewComponentResult is ViewBuffer viewBuffer)
        {
            // In the ordinary case, DefaultViewComponentHelper will return an instance of ViewBuffer. We can simply
            // invoke WriteToAsync on it.
            await viewBuffer.WriteToAsync(writer, _htmlEncoder);

            await writer.FlushAsync();
        }
        else
        {
            await using var bufferingStream = new FileBufferingWriteStream();
            await using (var intermediateWriter = _writerFactory.CreateWriter(bufferingStream, resolvedContentTypeEncoding))
            {
                viewComponentResult.WriteTo(intermediateWriter, _htmlEncoder);
            }

            await bufferingStream.DrainBufferAsync(response.Body);
        }
    }
Пример #15
0
    /// <summary>
    /// Executes the <see cref="JsonResult"/> and writes the response.
    /// </summary>
    /// <param name="context">The <see cref="ActionContext"/>.</param>
    /// <param name="result">The <see cref="JsonResult"/>.</param>
    /// <returns>A <see cref="Task"/> which will complete when writing has completed.</returns>
    public async Task ExecuteAsync(ActionContext context, JsonResult result)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (result == null)
        {
            throw new ArgumentNullException(nameof(result));
        }

        var jsonSerializerSettings = GetSerializerSettings(result);

        var response = context.HttpContext.Response;

        ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
            result.ContentType,
            response.ContentType,
            (DefaultContentType, Encoding.UTF8),
            MediaType.GetEncoding,
            out var resolvedContentType,
            out var resolvedContentTypeEncoding);

        response.ContentType = resolvedContentType;

        if (result.StatusCode != null)
        {
            response.StatusCode = result.StatusCode.Value;
        }

        Log.JsonResultExecuting(_logger, result.Value);

        var responseStream = response.Body;
        FileBufferingWriteStream?fileBufferingWriteStream = null;

        if (!_mvcOptions.SuppressOutputFormatterBuffering)
        {
            fileBufferingWriteStream = new FileBufferingWriteStream();
            responseStream           = fileBufferingWriteStream;
        }

        try
        {
            var value = result.Value;
            if (value != null && _asyncEnumerableReaderFactory.TryGetReader(value.GetType(), out var reader))
            {
                Log.BufferingAsyncEnumerable(_logger, value);
                try
                {
                    value = await reader(value, context.HttpContext.RequestAborted);
                }
                catch (OperationCanceledException) when(context.HttpContext.RequestAborted.IsCancellationRequested)
                {
                }
                if (context.HttpContext.RequestAborted.IsCancellationRequested)
                {
                    return;
                }
            }

            await using (var writer = _writerFactory.CreateWriter(responseStream, resolvedContentTypeEncoding))
            {
                using var jsonWriter           = new JsonTextWriter(writer);
                jsonWriter.ArrayPool           = _charPool;
                jsonWriter.CloseOutput         = false;
                jsonWriter.AutoCompleteOnClose = false;

                var jsonSerializer = JsonSerializer.Create(jsonSerializerSettings);

                jsonSerializer.Serialize(jsonWriter, value);
            }

            if (fileBufferingWriteStream != null)
            {
                await fileBufferingWriteStream.DrainBufferAsync(response.Body);
            }
        }
        finally
        {
            if (fileBufferingWriteStream != null)
            {
                await fileBufferingWriteStream.DisposeAsync();
            }
        }
    }
Пример #16
0
        /// <summary>
        /// Executes the <see cref="JsonResult"/> and writes the response.
        /// </summary>
        /// <param name="context">The <see cref="ActionContext"/>.</param>
        /// <param name="result">The <see cref="JsonResult"/>.</param>
        /// <returns>A <see cref="Task"/> which will complete when writing has completed.</returns>
        public async Task ExecuteAsync(ActionContext context, JsonResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            var jsonSerializerSettings = GetSerializerSettings(result);

            var response = context.HttpContext.Response;

            ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
                result.ContentType,
                response.ContentType,
                DefaultContentType,
                out var resolvedContentType,
                out var resolvedContentTypeEncoding);

            response.ContentType = resolvedContentType;

            if (result.StatusCode != null)
            {
                response.StatusCode = result.StatusCode.Value;
            }

            _logger.JsonResultExecuting(result.Value);

            var responseStream = response.Body;
            FileBufferingWriteStream fileBufferingWriteStream = null;

            if (!_mvcOptions.SuppressOutputFormatterBuffering)
            {
                fileBufferingWriteStream = new FileBufferingWriteStream();
                responseStream           = fileBufferingWriteStream;
            }

            try
            {
                await using (var writer = _writerFactory.CreateWriter(responseStream, resolvedContentTypeEncoding))
                {
                    using var jsonWriter           = new JsonTextWriter(writer);
                    jsonWriter.ArrayPool           = _charPool;
                    jsonWriter.CloseOutput         = false;
                    jsonWriter.AutoCompleteOnClose = false;

                    var jsonSerializer = JsonSerializer.Create(jsonSerializerSettings);
                    jsonSerializer.Serialize(jsonWriter, result.Value);
                }

                if (fileBufferingWriteStream != null)
                {
                    await fileBufferingWriteStream.DrainBufferAsync(response.Body);
                }
            }
            finally
            {
                if (fileBufferingWriteStream != null)
                {
                    await fileBufferingWriteStream.DisposeAsync();
                }
            }
        }