public async Task WriteToStreamAsync_UsesCorrectCharacterEncoding( string content, string encodingAsString, bool isDefaultEncoding) { // Arrange var formatter = new JsonOutputFormatter(); var formattedContent = "\"" + content + "\""; var mediaType = string.Format("application/json; charset={0}", encodingAsString); var encoding = CreateOrGetSupportedEncoding(formatter, encodingAsString, isDefaultEncoding); var expectedData = encoding.GetBytes(formattedContent); var body = new MemoryStream(); var actionContext = GetActionContext(MediaTypeHeaderValue.Parse(mediaType), body); var outputFormatterContext = new OutputFormatterContext { Object = content, DeclaredType = typeof(string), HttpContext = actionContext.HttpContext, SelectedEncoding = encoding }; // Act await formatter.WriteResponseBodyAsync(outputFormatterContext); // Assert var actualData = body.ToArray(); Assert.Equal(expectedData, actualData); }
public void SelectResponseCharacterEncoding_SelectsEncoding( string acceptCharsetHeaders, string requestEncoding, string[] supportedEncodings, string expectedEncoding) { // Arrange var mockHttpContext = new Mock<HttpContext>(); var httpRequest = new DefaultHttpContext().Request; httpRequest.Headers["Accept-Charset"] = acceptCharsetHeaders; httpRequest.ContentType = "application/acceptCharset;charset=" + requestEncoding; mockHttpContext.SetupGet(o => o.Request).Returns(httpRequest); var formatter = new TestOutputFormatter(); foreach (string supportedEncoding in supportedEncodings) { formatter.SupportedEncodings.Add(Encoding.GetEncoding(supportedEncoding)); } var formatterContext = new OutputFormatterContext() { Object = "someValue", HttpContext = mockHttpContext.Object, DeclaredType = typeof(string) }; // Act var actualEncoding = formatter.SelectCharacterEncoding(formatterContext); // Assert Assert.Equal(Encoding.GetEncoding(expectedEncoding), actualEncoding); }
public void WriteResponseContentHeaders_NoSupportedEncodings_NoEncodingIsSet() { // Arrange var formatter = new TestOutputFormatter(); var testContentType = MediaTypeHeaderValue.Parse("text/json"); formatter.SupportedEncodings.Clear(); formatter.SupportedMediaTypes.Clear(); formatter.SupportedMediaTypes.Add(testContentType); var formatterContext = new OutputFormatterContext() { HttpContext = new DefaultHttpContext(), }; // Act formatter.WriteResponseHeaders(formatterContext); // Assert Assert.Null(formatterContext.SelectedEncoding); Assert.Equal(testContentType, formatterContext.SelectedContentType); // If we had set an encoding, it would be part of the content type header Assert.Equal(testContentType, formatterContext.HttpContext.Response.GetTypedHeaders().ContentType); }
/// <inheritdoc /> public virtual bool CanWriteResult([NotNull] OutputFormatterContext context, MediaTypeHeaderValue contentType) { var runtimeType = context.Object == null ? null : context.Object.GetType(); if (!CanWriteType(context.DeclaredType, runtimeType)) { return(false); } MediaTypeHeaderValue mediaType = null; if (contentType == null) { // If the desired content type is set to null, the current formatter is free to choose the // response media type. mediaType = SupportedMediaTypes.FirstOrDefault(); } else { // Since supportedMedia Type is going to be more specific check if supportedMediaType is a subset // of the content type which is typically what we get on acceptHeader. mediaType = SupportedMediaTypes .FirstOrDefault(supportedMediaType => supportedMediaType.IsSubsetOf(contentType)); } if (mediaType != null) { context.SelectedContentType = mediaType; return(true); } return(false); }
public Task WriteAsync(OutputFormatterContext context) { var response = context.HttpContext.Response; response.ContentLength = 0; response.StatusCode = context.StatusCode ?? StatusCodes.Status204NoContent; return Task.FromResult(true); }
public void SelectResponseCharacterEncoding_SelectsEncoding( string acceptCharsetHeaders, string requestEncoding, string[] supportedEncodings, string expectedEncoding) { // Arrange var mockHttpContext = new Mock <HttpContext>(); var httpRequest = new DefaultHttpContext().Request; httpRequest.Headers["Accept-Charset"] = acceptCharsetHeaders; httpRequest.ContentType = "application/acceptCharset;charset=" + requestEncoding; mockHttpContext.SetupGet(o => o.Request).Returns(httpRequest); var formatter = new TestOutputFormatter(); foreach (string supportedEncoding in supportedEncodings) { formatter.SupportedEncodings.Add(Encoding.GetEncoding(supportedEncoding)); } var formatterContext = new OutputFormatterContext() { Object = "someValue", HttpContext = mockHttpContext.Object, DeclaredType = typeof(string) }; // Act var actualEncoding = formatter.SelectCharacterEncoding(formatterContext); // Assert Assert.Equal(Encoding.GetEncoding(expectedEncoding), actualEncoding); }
public async Task WriteAsync_DoesNotWriteNullStrings() { // Arrange Encoding encoding = Encoding.UTF8; var memoryStream = new MemoryStream(); var response = new Mock <HttpResponse>(); response.SetupProperty <long?>(o => o.ContentLength); response.SetupGet(r => r.Body).Returns(memoryStream); var mockHttpContext = new Mock <HttpContext>(); mockHttpContext.Setup(o => o.Response).Returns(response.Object); var formatter = new StringOutputFormatter(); var formatterContext = new OutputFormatterContext() { Object = null, DeclaredType = typeof(string), HttpContext = mockHttpContext.Object, SelectedEncoding = encoding }; // Act await formatter.WriteResponseBodyAsync(formatterContext); // Assert Assert.Equal(0, memoryStream.Length); response.VerifySet(r => r.ContentLength = It.IsAny <long?>(), Times.Never()); }
/// <inheritdoc /> public Task WriteAsync(OutputFormatterContext context) { var response = context.HttpContext.Response; response.StatusCode = StatusCodes.Status406NotAcceptable; return(Task.FromResult(true)); }
public async Task WriteAsync_DoesNotWriteNullStrings() { // Arrange Encoding encoding = Encoding.UTF8; var memoryStream = new MemoryStream(); var response = new Mock<HttpResponse>(); response.SetupProperty<long?>(o => o.ContentLength); response.SetupGet(r => r.Body).Returns(memoryStream); var mockHttpContext = new Mock<HttpContext>(); mockHttpContext.Setup(o => o.Response).Returns(response.Object); var formatter = new StringOutputFormatter(); var formatterContext = new OutputFormatterContext() { Object = null, DeclaredType = typeof(string), HttpContext = mockHttpContext.Object, SelectedEncoding = encoding }; // Act await formatter.WriteResponseBodyAsync(formatterContext); // Assert Assert.Equal(0, memoryStream.Length); response.VerifySet(r => r.ContentLength = It.IsAny<long?>(), Times.Never()); }
public Task WriteAsync(OutputFormatterContext context) { var response = context.HttpContext.Response; response.ContentLength = 0; response.StatusCode = context.StatusCode ?? StatusCodes.Status204NoContent; return(Task.FromResult(true)); }
public async Task WriteAsync(OutputFormatterContext context) { var response = context.HttpContext.Response; var responseMessage = context.Object as HttpResponseMessage; if (responseMessage == null) { var message = Resources.FormatHttpResponseMessageFormatter_UnsupportedType( nameof(HttpResponseMessageOutputFormatter), nameof(HttpResponseMessage)); throw new InvalidOperationException(message); } using (responseMessage) { response.StatusCode = (int)responseMessage.StatusCode; var responseFeature = context.HttpContext.Features.Get<IHttpResponseFeature>(); if (responseFeature != null) { responseFeature.ReasonPhrase = responseMessage.ReasonPhrase; } var responseHeaders = responseMessage.Headers; // Ignore the Transfer-Encoding header if it is just "chunked". // We let the host decide about whether the response should be chunked or not. if (responseHeaders.TransferEncodingChunked == true && responseHeaders.TransferEncoding.Count == 1) { responseHeaders.TransferEncoding.Clear(); } foreach (var header in responseHeaders) { response.Headers.Append(header.Key, header.Value.ToArray()); } if (responseMessage.Content != null) { var contentHeaders = responseMessage.Content.Headers; // Copy the response content headers only after ensuring they are complete. // We ask for Content-Length first because HttpContent lazily computes this // and only afterwards writes the value into the content headers. var unused = contentHeaders.ContentLength; foreach (var header in contentHeaders) { response.Headers.Append(header.Key, header.Value.ToArray()); } await responseMessage.Content.CopyToAsync(response.Body); } } }
/// <inheritdoc /> public bool CanWriteResult([NotNull] OutputFormatterContext context, MediaTypeHeaderValue contentType) { // Ignore the passed in content type, if the object is a Stream. if (context.Object is Stream) { context.SelectedContentType = contentType; return(true); } return(false); }
public bool CanWriteResult(OutputFormatterContext context, MediaTypeHeaderValue contentType) { // ignore the contentType and just look at the content. // This formatter will be selected if the content is null. // We check for Task as a user can directly create an ObjectContentResult with the unwrapped type. if (context.DeclaredType == typeof(void) || context.DeclaredType == typeof(Task)) { return(true); } return(TreatNullValueAsNoContent && context.Object == null); }
public override bool CanWriteResult(OutputFormatterContext context, MediaTypeHeaderValue contentType) { if (base.CanWriteResult(context, contentType)) { var actionReturnString = context.Object as string; if (actionReturnString != null) { return true; } } return false; }
public bool CanWriteResult(OutputFormatterContext context, MediaTypeHeaderValue contentType) { // ignore the contentType and just look at the content. // This formatter will be selected if the content is null. // We check for Task as a user can directly create an ObjectContentResult with the unwrapped type. if (context.DeclaredType == typeof(void) || context.DeclaredType == typeof(Task)) { return true; } return TreatNullValueAsNoContent && context.Object == null; }
public override async Task WriteResponseBodyAsync(OutputFormatterContext context) { var contact = (Contact)context.Object; var builder = new StringBuilder(); builder.AppendLine("BEGIN:VCARD"); builder.AppendFormat("FN:{0}", contact.Name); builder.AppendLine(); builder.AppendLine("END:VCARD"); await context.HttpContext.Response.WriteAsync(builder.ToString(), context.SelectedEncoding); }
public override Task WriteResponseBodyAsync(OutputFormatterContext context) { var valueAsString = (string)context.Object; if (string.IsNullOrEmpty(valueAsString)) { return TaskCache.CompletedTask; } var response = context.HttpContext.Response; return response.WriteAsync(valueAsString, context.SelectedEncoding); }
public override Task WriteResponseBodyAsync(OutputFormatterContext context) { var valueAsString = (string)context.Object; if (string.IsNullOrEmpty(valueAsString)) { return(TaskCache.CompletedTask); } var response = context.HttpContext.Response; return(response.WriteAsync(valueAsString, context.SelectedEncoding)); }
public void CanWriteResult_ForNullContentType_UsesFirstEntryInSupportedContentTypes() { // Arrange var context = new OutputFormatterContext(); var formatter = new TestOutputFormatter(); // Act var result = formatter.CanWriteResult(context, null); // Assert Assert.True(result); Assert.Equal(formatter.SupportedMediaTypes[0].ToString(), context.SelectedContentType.ToString()); }
public override bool CanWriteResult(OutputFormatterContext context, MediaTypeHeaderValue contentType) { // Ignore the passed in content type, if the object is string // always return it as a text/plain format. if (context.DeclaredType == typeof(string)) { return(true); } if (context.Object is string) { return(true); } return(false); }
public void CanWriteResult_SetsContentType() { // Arrange var formatter = new StreamOutputFormatter(); var contentType = new MediaTypeHeaderValue("text/plain"); var context = new OutputFormatterContext(); context.Object = new MemoryStream(); // Act var result = formatter.CanWriteResult(context, contentType); // Assert Assert.True(result); Assert.Same(contentType, context.SelectedContentType); }
public void CanWriteResult_OnlyActsOnStreams(Type type) { // Arrange var formatter = new StreamOutputFormatter(); var context = new OutputFormatterContext(); var contentType = new MediaTypeHeaderValue("text/plain"); context.Object = type != null?Activator.CreateInstance(type) : null; // Act var result = formatter.CanWriteResult(context, contentType); // Assert Assert.False(result); Assert.Null(context.SelectedContentType); }
public override bool CanWriteResult(OutputFormatterContext context, MediaTypeHeaderValue contentType) { // Ignore the passed in content type, if the object is string // always return it as a text/plain format. if (context.DeclaredType == typeof(string)) { return true; } if (context.Object is string) { return true; } return false; }
public void CanWriteResult_OnlyActsOnStreams(Type type) { // Arrange var formatter = new StreamOutputFormatter(); var context = new OutputFormatterContext(); var contentType = new MediaTypeHeaderValue("text/plain"); context.Object = type != null ? Activator.CreateInstance(type) : null; // Act var result = formatter.CanWriteResult(context, contentType); // Assert Assert.False(result); Assert.Null(context.SelectedContentType); }
public void CanWriteResult_ReturnsTrue_ForStreams(Type declaredType, string contentType) { // Arrange var formatter = new StreamOutputFormatter(); var contentTypeHeader = contentType == null ? null : new MediaTypeHeaderValue(contentType); var formatterContext = new OutputFormatterContext() { DeclaredType = declaredType, Object = new MemoryStream() }; // Act var canWrite = formatter.CanWriteResult(formatterContext, contentTypeHeader); // Assert Assert.True(canWrite); }
public override Task WriteResponseBodyAsync(OutputFormatterContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var response = context.HttpContext.Response; var selectedEncoding = context.SelectedEncoding; using (var writer = new HttpResponseStreamWriter(response.Body, selectedEncoding)) { WriteObject(writer, context.Object); } return(Task.FromResult(true)); }
public void CanWriteResult_OnlyActsOnStreams_IgnoringContentType(Type declaredType, string contentType) { // Arrange var formatter = new StreamOutputFormatter(); var contentTypeHeader = contentType == null ? null : new MediaTypeHeaderValue(contentType); var formatterContext = new OutputFormatterContext() { DeclaredType = declaredType, Object = new SimplePOCO() }; // Act var canWrite = formatter.CanWriteResult(formatterContext, contentTypeHeader); // Assert Assert.False(canWrite); }
/// <inheritdoc /> public async Task WriteAsync([NotNull] OutputFormatterContext context) { using (var valueAsStream = ((Stream)context.Object)) { var response = context.HttpContext.Response; if (context.SelectedContentType != null) { response.ContentType = context.SelectedContentType.ToString(); } var bufferingFeature = context.HttpContext.Features.Get <IHttpBufferingFeature>(); bufferingFeature?.DisableResponseBuffering(); await valueAsStream.CopyToAsync(response.Body); } }
public void CanWriteResult_ReturnsTrueForStringTypes(object value, bool useDeclaredTypeAsString, bool expectedCanWriteResult) { // Arrange var formatter = new StringOutputFormatter(); var typeToUse = useDeclaredTypeAsString ? typeof(string) : typeof(object); var formatterContext = new OutputFormatterContext() { Object = value, DeclaredType = typeToUse }; // Act var result = formatter.CanWriteResult(formatterContext, null); // Assert Assert.Equal(expectedCanWriteResult, result); }
public void CanWriteResult_ReturnsTrue_IfReturnTypeIsVoidOrTask(Type declaredType) { // Arrange var formatterContext = new OutputFormatterContext() { Object = "Something non null.", DeclaredType = declaredType, HttpContext = null, }; var contetType = MediaTypeHeaderValue.Parse("text/plain"); var formatter = new HttpNoContentOutputFormatter(); // Act var actualCanWriteResult = formatter.CanWriteResult(formatterContext, contetType); // Assert Assert.True(actualCanWriteResult); }
public async Task WriteAsync_WritesTheStatusCode204() { // Arrange var defaultHttpContext = new DefaultHttpContext(); var formatterContext = new OutputFormatterContext() { Object = null, HttpContext = defaultHttpContext, }; var formatter = new HttpNoContentOutputFormatter(); // Act await formatter.WriteAsync(formatterContext); // Assert Assert.Equal(StatusCodes.Status204NoContent, defaultHttpContext.Response.StatusCode); }
public async Task WriteAsync_ContextStatusCodeSet_WritesSameStatusCode() { // Arrange var defaultHttpContext = new DefaultHttpContext(); var formatterContext = new OutputFormatterContext() { Object = null, HttpContext = defaultHttpContext, StatusCode = StatusCodes.Status201Created }; var formatter = new HttpNoContentOutputFormatter(); // Act await formatter.WriteAsync(formatterContext); // Assert Assert.Equal(StatusCodes.Status201Created, defaultHttpContext.Response.StatusCode); }
public void CanWrite_ReturnsFalse_ForUnsupportedType() { // Arrange var context = new OutputFormatterContext(); context.DeclaredType = typeof(string); context.Object = "Hello, world!"; var formatter = new TypeSpecificFormatter(); formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/json")); formatter.SupportedTypes.Add(typeof(int)); // Act var result = formatter.CanWriteResult(context, formatter.SupportedMediaTypes[0]); // Assert Assert.False(result); }
public async Task WriteResponseHeaders_ClonesMediaType() { // Arrange var formatter = new PngImageFormatter(); formatter.SupportedMediaTypes.Clear(); var mediaType = new MediaTypeHeaderValue("image/png"); formatter.SupportedMediaTypes.Add(mediaType); var formatterContext = new OutputFormatterContext(); formatterContext.HttpContext = new DefaultHttpContext(); // Act await formatter.WriteAsync(formatterContext); // Assert Assert.NotSame(mediaType, formatterContext.SelectedContentType); Assert.Null(mediaType.Charset); Assert.Equal("image/png; charset=utf-8", formatterContext.SelectedContentType.ToString()); }
public void WriteResponseContentHeaders_NoSelectedContentType_SetsOutputFormatterContext() { // Arrange var testFormatter = new DoesNotSetContext(); var testContentType = MediaTypeHeaderValue.Parse("application/doesNotSetContext"); var formatterContext = new OutputFormatterContext(); var mockHttpContext = new Mock <HttpContext>(); var httpRequest = new DefaultHttpContext().Request; mockHttpContext.SetupGet(o => o.Request).Returns(httpRequest); mockHttpContext.SetupProperty(o => o.Response.ContentType); formatterContext.HttpContext = mockHttpContext.Object; // Act testFormatter.WriteResponseHeaders(formatterContext); // Assert Assert.Equal(Encoding.Unicode.WebName, formatterContext.SelectedEncoding.WebName); Assert.Equal(Encoding.Unicode, formatterContext.SelectedEncoding); Assert.Equal("application/doesNotSetContext; charset=" + Encoding.Unicode.WebName, formatterContext.SelectedContentType.ToString()); }
/// <summary> /// Sets the headers on <see cref="Microsoft.AspNet.Http.HttpResponse"/> object. /// </summary> /// <param name="context">The formatter context associated with the call.</param> public virtual void WriteResponseHeaders([NotNull] OutputFormatterContext context) { var selectedMediaType = context.SelectedContentType; // If content type is not set then set it based on supported media types. selectedMediaType = selectedMediaType ?? SupportedMediaTypes.FirstOrDefault(); if (selectedMediaType == null) { throw new InvalidOperationException(Resources.FormatOutputFormatterNoMediaType(GetType().FullName)); } // Copy the media type as we don't want it to affect the next request selectedMediaType = selectedMediaType.Copy(); // Not text-based media types will use an encoding/charset - binary formats just ignore it. We want to // make this class work with media types that use encodings, and those that don't. // // The default implementation of SelectCharacterEncoding will read from the list of SupportedEncodings // and will always choose a default encoding if any are supported. So, the only cases where the // selectedEncoding can be null are: // // 1). No supported encodings - we assume this is a non-text format // 2). Custom implementation of SelectCharacterEncoding - trust the user and give them what they want. var selectedEncoding = SelectCharacterEncoding(context); if (selectedEncoding != null) { context.SelectedEncoding = selectedEncoding; // Override the content type value even if one already existed. selectedMediaType.Charset = selectedEncoding.WebName; } context.SelectedContentType = context.SelectedContentType ?? selectedMediaType; var response = context.HttpContext.Response; response.ContentType = selectedMediaType.ToString(); }
/// <inheritdoc /> public override Task WriteResponseBodyAsync(OutputFormatterContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var response = context.HttpContext.Response; var tempWriterSettings = WriterSettings.Clone(); tempWriterSettings.Encoding = context.SelectedEncoding; using (var xmlWriter = CreateXmlWriter(context.HttpContext.Response.Body, tempWriterSettings)) { var obj = context.Object; var runtimeType = obj?.GetType(); var resolvedType = ResolveType(context.DeclaredType, runtimeType); var wrappingType = GetSerializableType(resolvedType); // Wrap the object only if there is a wrapping type. if (wrappingType != null && wrappingType != resolvedType) { var wrapperProvider = WrapperProviderFactories.GetWrapperProvider( new WrapperProviderContext( declaredType: resolvedType, isSerialization: true)); obj = wrapperProvider.Wrap(obj); } var xmlSerializer = GetCachedSerializer(wrappingType); xmlSerializer.Serialize(xmlWriter, obj); } return(Task.FromResult(true)); }
/// <summary> /// Determines the best <see cref="Encoding"/> amongst the supported encodings /// for reading or writing an HTTP entity body based on the provided <paramref name="contentTypeHeader"/>. /// </summary> /// <param name="context">The formatter context associated with the call. /// </param> /// <returns>The <see cref="Encoding"/> to use when reading the request or writing the response.</returns> public virtual Encoding SelectCharacterEncoding([NotNull] OutputFormatterContext context) { var request = context.HttpContext.Request; var encoding = MatchAcceptCharacterEncoding(request.GetTypedHeaders().AcceptCharset); if (encoding == null) { // Match based on request acceptHeader. MediaTypeHeaderValue requestContentType = null; if (MediaTypeHeaderValue.TryParse(request.ContentType, out requestContentType) && !string.IsNullOrEmpty(requestContentType.Charset)) { var requestCharset = requestContentType.Charset; encoding = SupportedEncodings.FirstOrDefault( supportedEncoding => requestCharset.Equals(supportedEncoding.WebName)); } } encoding = encoding ?? SupportedEncodings.FirstOrDefault(); return(encoding); }
public void CanWriteResult_ByDefault_ReturnsTrue_IfTheValueIsNull( object value, bool declaredTypeAsString, bool expectedCanwriteResult, bool useNonNullContentType) { // Arrange var typeToUse = declaredTypeAsString ? typeof(string) : typeof(object); var formatterContext = new OutputFormatterContext() { Object = value, DeclaredType = typeToUse, HttpContext = null, }; var contetType = useNonNullContentType ? MediaTypeHeaderValue.Parse("text/plain") : null; var formatter = new HttpNoContentOutputFormatter(); // Act var actualCanWriteResult = formatter.CanWriteResult(formatterContext, contetType); // Assert Assert.Equal(expectedCanwriteResult, actualCanWriteResult); }
CanWriteResult_ReturnsTrue_IfReturnValueIsNullAndTreatNullValueAsNoContentIsNotSet(string value, bool treatNullValueAsNoContent, bool expectedCanwriteResult) { // Arrange var formatterContext = new OutputFormatterContext() { Object = value, DeclaredType = typeof(string), HttpContext = null, }; var contetType = MediaTypeHeaderValue.Parse("text/plain"); var formatter = new HttpNoContentOutputFormatter() { TreatNullValueAsNoContent = treatNullValueAsNoContent }; // Act var actualCanWriteResult = formatter.CanWriteResult(formatterContext, contetType); // Assert Assert.Equal(expectedCanwriteResult, actualCanWriteResult); }
/// <inheritdoc /> public Task WriteAsync(OutputFormatterContext context) { var response = context.HttpContext.Response; response.StatusCode = StatusCodes.Status406NotAcceptable; return Task.FromResult(true); }
public override Task WriteResponseBodyAsync(OutputFormatterContext context) { WriteObject(context.HttpContext.Response.Body, context.Object); return Task.FromResult(true); }
/// <inheritdoc /> public bool CanWriteResult(OutputFormatterContext context, MediaTypeHeaderValue contentType) { return context.FailedContentNegotiation ?? false; }
/// <inheritdoc /> public override Task WriteResponseBodyAsync(OutputFormatterContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var response = context.HttpContext.Response; var tempWriterSettings = WriterSettings.Clone(); tempWriterSettings.Encoding = context.SelectedEncoding; using (var xmlWriter = CreateXmlWriter(context.HttpContext.Response.Body, tempWriterSettings)) { var obj = context.Object; var runtimeType = obj?.GetType(); var resolvedType = ResolveType(context.DeclaredType, runtimeType); var wrappingType = GetSerializableType(resolvedType); // Wrap the object only if there is a wrapping type. if (wrappingType != null && wrappingType != resolvedType) { var wrapperProvider = WrapperProviderFactories.GetWrapperProvider( new WrapperProviderContext( declaredType: resolvedType, isSerialization: true)); obj = wrapperProvider.Wrap(obj); } var xmlSerializer = GetCachedSerializer(wrappingType); xmlSerializer.Serialize(xmlWriter, obj); } return Task.FromResult(true); }
public override Task WriteResponseBodyAsync(OutputFormatterContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var response = context.HttpContext.Response; var selectedEncoding = context.SelectedEncoding; using (var writer = new HttpResponseStreamWriter(response.Body, selectedEncoding)) { WriteObject(writer, context.Object); } return Task.FromResult(true); }
public async Task DisablesResponseBuffering_IfBufferingFeatureAvailable() { // Arrange var expected = Encoding.UTF8.GetBytes("Test data"); var formatter = new StreamOutputFormatter(); var httpContext = new DefaultHttpContext(); var ms = new MemoryStream(); httpContext.Response.Body = ms; var bufferingFeature = new TestBufferingFeature(); httpContext.Features.Set<IHttpBufferingFeature>(bufferingFeature); var context = new OutputFormatterContext(); context.Object = new MemoryStream(expected); context.HttpContext = httpContext; // Act await formatter.WriteAsync(context); // Assert Assert.Equal(expected, ms.ToArray()); Assert.True(bufferingFeature.DisableResponseBufferingInvoked); }
public override Task WriteResponseBodyAsync(OutputFormatterContext context) { throw new NotImplementedException(); }
public bool CanWriteResult(OutputFormatterContext context, MediaTypeHeaderValue contentType) { return context.Object is HttpResponseMessage; }
public override async Task WriteResponseBodyAsync(OutputFormatterContext context) { var response = context.HttpContext.Response; response.ContentType = "text/plain;charset=utf-8"; await response.WriteAsync(context.Object as string); }