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(); } } }
public async Task ExecuteAsync_UsesContentType_FromPartialViewResult() { // Arrange var context = GetActionContext(); var executor = GetViewExecutor(); var contentType = "application/x-my-content-type"; var viewResult = new PartialViewResult { ViewName = "my-view", ContentType = contentType, ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()), TempData = Mock.Of <ITempDataDictionary>(), }; // Act await executor.ExecuteAsync(context, Mock.Of <IView>(), viewResult); // Assert Assert.Equal("application/x-my-content-type", context.HttpContext.Response.ContentType); // Check if the original instance provided by the user has not changed. // Since we do not have access to the new instance created within the view executor, // check if at least the content is the same. Assert.Null(MediaType.GetEncoding(contentType)); }
/// <summary> /// Gets the content type and encoding that need to be used for the response. /// The priority for selecting the content type is: /// 1. ContentType property set on the action result /// 2. <see cref="HttpResponse.ContentType"/> property set on <see cref="HttpResponse"/> /// 3. Default content type set on the action result /// </summary> /// <remarks> /// The user supplied content type is not modified and is used as is. For example, if user /// sets the content type to be "text/plain" without any encoding, then the default content type's /// encoding is used to write the response and the ContentType header is set to be "text/plain" without any /// "charset" information. /// </remarks> /// <param name="actionResultContentType">ContentType set on the action result</param> /// <param name="httpResponseContentType"><see cref="HttpResponse.ContentType"/> property set /// on <see cref="HttpResponse"/></param> /// <param name="defaultContentType">The default content type of the action result.</param> /// <param name="resolvedContentType">The content type to be used for the response content type header</param> /// <param name="resolvedContentTypeEncoding">Encoding to be used for writing the response</param> public static void ResolveContentTypeAndEncoding(string actionResultContentType, string httpResponseContentType, string defaultContentType, out string resolvedContentType, out Encoding resolvedContentTypeEncoding) { var defaultContentTypeEncoding = MediaType.GetEncoding(defaultContentType); // 1. User sets the ContentType property on the action result if (actionResultContentType != null) { resolvedContentType = actionResultContentType; var actionResultEncoding = MediaType.GetEncoding(actionResultContentType); resolvedContentTypeEncoding = actionResultEncoding ?? defaultContentTypeEncoding; return; } // 2. User sets the ContentType property on the http response directly if (!string.IsNullOrEmpty(httpResponseContentType)) { var mediaTypeEncoding = MediaType.GetEncoding(httpResponseContentType); if (mediaTypeEncoding != null) { resolvedContentType = httpResponseContentType; resolvedContentTypeEncoding = mediaTypeEncoding; } else { resolvedContentType = httpResponseContentType; resolvedContentTypeEncoding = defaultContentTypeEncoding; } return; } // 3. Fall-back to the default content type resolvedContentType = defaultContentType; resolvedContentTypeEncoding = defaultContentTypeEncoding; }
public async Task WriteAsync(OutputFormatterWriteContext context) { var response = context.HttpContext.Response; var contentType = GetNonEmptyString(context.ContentType.Value, response.ContentType, JSONContentType); var encoding = MediaType.GetEncoding(contentType) ?? jsonFormatter.Encoding; if (JSONContentType.Equals(contentType, StringComparison.InvariantCultureIgnoreCase)) { contentType = $"{JSONContentType};charset={encoding.HeaderName}"; } response.ContentType = contentType; if (encoding == jsonFormatter.Encoding || encoding.Equals(jsonFormatter.Encoding)) { var s = response.Body; await jsonFormatter.SerializeAsync(context.Object, s); await s.FlushAsync(); } else { var tw = context.WriterFactory(response.Body, encoding); await jsonFormatter.SerializeAsync(context.Object, tw); await tw.FlushAsync(); } }
public async Task ExecuteAsync(ActionContext context, TJsonResult result) { var value = valueProperty.GetValue(result); var settings = settingsProperty.GetValue(result); var status = statusProperty.GetValue(result); var contentType = Convert.ToString(contentTypeProperty.GetValue(result)); var response = context.HttpContext.Response; if (!(settings is JsonFormatter jsonFormatter)) { jsonFormatter = this.jsonFormatter; } contentType = GetNonEmptyString(contentType, response.ContentType, JSONUTF8ContentType); var encoding = MediaType.GetEncoding(contentType); response.ContentType = contentType; if (status is int status_code) { response.StatusCode = status_code; } var writer = new StreamWriter(response.Body, encoding); await jsonFormatter.SerializeAsync(value, writer); await writer.FlushAsync(); }
public async Task <InputFormatterResult> ReadAsync(InputFormatterContext context) { var request = context.HttpContext.Request; var contentType = request.ContentType; var encoding = MediaType.GetEncoding(contentType) ?? jsonFormatter.Encoding; object result; if (encoding == jsonFormatter.Encoding || encoding.Equals(jsonFormatter.Encoding)) { result = await jsonFormatter.DeserializeAsync(request.Body, context.ModelType); } else { var tr = context.ReaderFactory(request.Body, encoding); result = await jsonFormatter.DeserializeAsync(tr, context.ModelType); } if (result == null && !context.TreatEmptyInputAsDefaultValue) { return(InputFormatterResult.NoValue()); } else { return(InputFormatterResult.Success(result)); } }
public async Task ExecuteResult(Controller controller) { var response = controller.Context.Response; if (string.IsNullOrEmpty(ViewName)) { ViewName = (string)controller.RouteValues["action"]; } if (ViewRenderService == null) { ViewRenderService = controller.Context.RequestServices.GetService <IViewRenderService>(); } var content = await ViewRenderService.RenderAsync(ViewName, Model, controller); var encoding = MediaType.GetEncoding(_defaultContentType); response.ContentType = _defaultContentType; if (StatusCode != null) { response.StatusCode = StatusCode.Value; } if (content != null) { response.ContentLength = encoding.GetByteCount(content); await response.WriteAsync(content, encoding); } await response.CompleteAsync(); }
public async Task ExecuteResult(Controller controller) { var response = controller.Context.Response; if (ContentType == null) { if (!string.IsNullOrEmpty(response.ContentType)) { ContentType = response.ContentType; } else { ContentType = _defaultContentType; } } var encoding = MediaType.GetEncoding(ContentType) ?? MediaType.GetEncoding(_defaultContentType); response.ContentType = ContentType; if (StatusCode != null) { response.StatusCode = StatusCode.Value; } if (Content != null) { response.ContentLength = encoding.GetByteCount(Content); await response.WriteAsync(Content, encoding); } await response.CompleteAsync(); }
private async Task<string> ReadBody(Stream body, string contentType) { var encoding = contentType != null ? MediaType.GetEncoding(contentType) ?? Encoding.UTF8 : Encoding.UTF8; using (var bodyReader = new StreamReader(body, encoding)) { return await bodyReader.ReadToEndAsync().ConfigureAwait(false); } }
public async Task WriteAsync(OutputFormatterWriteContext context) { var response = context.HttpContext.Response; var contentType = GetNonEmptyString(context.ContentType.Value, response.ContentType, JSONUTF8ContentType); response.ContentType = contentType; var encoding = MediaType.GetEncoding(contentType); var writer = context.WriterFactory(response.Body, encoding); await jsonFormatter.SerializeAsync(context.Object, writer); await writer.FlushAsync(); }
public void ApiController_Json_Encoding() { // Arrange var controller = new ConcreteApiController(); var product = new Product(); var settings = new JsonSerializerSettings(); // Act var result = controller.Json(product, settings, Encoding.UTF8); // Assert var jsonResult = Assert.IsType <JsonResult>(result); Assert.Same(product, jsonResult.Value); Assert.Same(Encoding.UTF8, MediaType.GetEncoding(jsonResult.ContentType)); }
public void ControllerContent_InvokedInUnitTests() { // Arrange var content = "Content_1"; var contentType = "text/asp"; var encoding = Encoding.ASCII; var controller = new TestabilityController(); // Act var result = controller.Content_Action(content, contentType, encoding); // Assert Assert.NotNull(result); var contentResult = Assert.IsType<ContentResult>(result); Assert.Equal(content, contentResult.Content); Assert.Equal("text/asp; charset=us-ascii", contentResult.ContentType.ToString()); Assert.Equal(encoding, MediaType.GetEncoding(contentResult.ContentType)); }
public async Task ExecuteAsync(ActionContext context, JsonResult result) { var response = context.HttpContext.Response; var jsonFormatter = #if NETCOREAPP (result.SerializerSettings as JsonFormatter) ?? #endif DefaultJsonFormatter; var contentType = GetNonEmptyString(result.ContentType, response.ContentType, JSONContentType); var encoding = MediaType.GetEncoding(contentType) ?? jsonFormatter.Encoding; if (JSONContentType.Equals(contentType, StringComparison.InvariantCultureIgnoreCase)) { contentType = $"{JSONContentType};charset={encoding.HeaderName}"; } response.ContentType = contentType; if (result.StatusCode != null) { response.StatusCode = result.StatusCode.Value; } if (encoding == jsonFormatter.Encoding || encoding.Equals(jsonFormatter.Encoding)) { var s = response.Body; await jsonFormatter.SerializeAsync(result.Value, s); await s.FlushAsync(); } else { var sw = new StreamWriter(response.Body, encoding); await jsonFormatter.SerializeAsync(result, sw); await sw.FlushAsync(); } }
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(); } }
public static void ResolveContentTypeAndEncoding( string actionResultContentType, string httpResponseContentType, string defaultContentType, out string resolvedContentType, out Encoding resolvedContentTypeEncoding) { var defaultContentTypeEncoding = MediaType.GetEncoding(defaultContentType); if (actionResultContentType != null) { resolvedContentType = actionResultContentType; var actionResultEncoding = MediaType.GetEncoding(actionResultContentType); resolvedContentTypeEncoding = actionResultEncoding ?? defaultContentTypeEncoding; return; } if (!string.IsNullOrEmpty(httpResponseContentType)) { var mediaTypeEncoding = MediaType.GetEncoding(httpResponseContentType); if (mediaTypeEncoding != null) { resolvedContentType = httpResponseContentType; resolvedContentTypeEncoding = mediaTypeEncoding; } else { resolvedContentType = httpResponseContentType; resolvedContentTypeEncoding = defaultContentTypeEncoding; } return; } resolvedContentType = defaultContentType; resolvedContentTypeEncoding = defaultContentTypeEncoding; }