internal static IList <StringWithQualityHeaderValue> GetAcceptCharsetHeaderValues(OutputFormatterWriteContext context) { var request = context.HttpContext.Request; if (StringWithQualityHeaderValue.TryParseList(request.Headers.AcceptCharset, out var result)) { return(result); } return(Array.Empty <StringWithQualityHeaderValue>()); }
/// <summary> /// Called during serialization to create the <see cref="JsonSerializer"/>.The formatter context /// that is passed gives an ability to create serializer specific to the context. /// </summary> /// <param name="context">A context object for <see cref="IOutputFormatter.WriteAsync(OutputFormatterWriteContext)"/>.</param> /// <returns>The <see cref="JsonSerializer"/> used during serialization and deserialization.</returns> protected virtual JsonSerializer CreateJsonSerializer(OutputFormatterWriteContext context) { return(CreateJsonSerializer()); }
/// <summary> /// Writes the response body. /// </summary> /// <param name="context">The formatter context associated with the call.</param> /// <param name="selectedEncoding">The <see cref="Encoding"/> that should be used to write the response.</param> /// <returns>A task which can write the response body.</returns> public abstract Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding);
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context) { throw new NotImplementedException(); }
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context) { return(Task.FromResult(true)); }
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) => _jsonOutputFormatter.WriteResponseBodyAsync(context, selectedEncoding);
/// <summary> /// Writes the response body. /// </summary> /// <param name="context">The formatter context associated with the call.</param> /// <returns>A task which can write the response body.</returns> public abstract Task WriteResponseBodyAsync(OutputFormatterWriteContext context);
/// <inheritdoc /> public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (selectedEncoding == null) { throw new ArgumentNullException(nameof(selectedEncoding)); } var writerSettings = WriterSettings.Clone(); writerSettings.Encoding = selectedEncoding; var httpContext = context.HttpContext; var response = httpContext.Response; _mvcOptions ??= httpContext.RequestServices.GetRequiredService <IOptions <MvcOptions> >().Value; _asyncEnumerableReaderFactory ??= new AsyncEnumerableReader(_mvcOptions); var value = context.Object; var valueType = context.ObjectType; if (value is not null && _asyncEnumerableReaderFactory.TryGetReader(value.GetType(), out var reader)) { Log.BufferingAsyncEnumerable(_logger, value); value = await reader(value); valueType = value.GetType(); } // Wrap the object only if there is a wrapping type. var wrappingType = GetSerializableType(valueType); if (wrappingType != null && wrappingType != valueType) { var wrapperProvider = WrapperProviderFactories.GetWrapperProvider(new WrapperProviderContext( declaredType: valueType, isSerialization: true)); value = wrapperProvider.Wrap(value); } var xmlSerializer = GetCachedSerializer(wrappingType); var responseStream = response.Body; FileBufferingWriteStream fileBufferingWriteStream = null; if (!_mvcOptions.SuppressOutputFormatterBuffering) { fileBufferingWriteStream = new FileBufferingWriteStream(); responseStream = fileBufferingWriteStream; } try { await using (var textWriter = context.WriterFactory(responseStream, selectedEncoding)) { using var xmlWriter = CreateXmlWriter(context, textWriter, writerSettings); Serialize(xmlSerializer, xmlWriter, value); } if (fileBufferingWriteStream != null) { response.ContentLength = fileBufferingWriteStream.Length; await fileBufferingWriteStream.DrainBufferAsync(response.BodyWriter); } } finally { if (fileBufferingWriteStream != null) { await fileBufferingWriteStream.DisposeAsync(); } } }
public override Encoding SelectCharacterEncoding(OutputFormatterWriteContext context) { return(_encoding); }
/// <inheritdoc /> public sealed override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (selectedEncoding == null) { throw new ArgumentNullException(nameof(selectedEncoding)); } var httpContext = context.HttpContext; // context.ObjectType reflects the declared model type when specified. // For polymorphic scenarios where the user declares a return type, but returns a derived type, // we want to serialize all the properties on the derived type. This keeps parity with // the behavior you get when the user does not declare the return type and with Json.Net at least at the top level. var objectType = context.Object?.GetType() ?? context.ObjectType ?? typeof(object); var responseStream = httpContext.Response.Body; if (selectedEncoding.CodePage == Encoding.UTF8.CodePage) { await JsonSerializer.SerializeAsync(responseStream, context.Object, objectType, SerializerOptions); await responseStream.FlushAsync(); } else { // JsonSerializer only emits UTF8 encoded output, but we need to write the response in the encoding specified by // selectedEncoding var transcodingStream = Encoding.CreateTranscodingStream(httpContext.Response.Body, selectedEncoding, Encoding.UTF8, leaveOpen: true); ExceptionDispatchInfo?exceptionDispatchInfo = null; try { await JsonSerializer.SerializeAsync(transcodingStream, context.Object, objectType, SerializerOptions); await transcodingStream.FlushAsync(); } catch (Exception ex) { // TranscodingStream may write to the inner stream as part of it's disposal. // We do not want this exception "ex" to be eclipsed by any exception encountered during the write. We will stash it and // explicitly rethrow it during the finally block. exceptionDispatchInfo = ExceptionDispatchInfo.Capture(ex); } finally { try { await transcodingStream.DisposeAsync(); } catch when(exceptionDispatchInfo != null) { } exceptionDispatchInfo?.Throw(); } } }
/// <inheritdoc /> public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (selectedEncoding == null) { throw new ArgumentNullException(nameof(selectedEncoding)); } // Compat mode for derived options _jsonOptions ??= context.HttpContext.RequestServices.GetRequiredService <IOptions <MvcNewtonsoftJsonOptions> >().Value; var response = context.HttpContext.Response; var responseStream = response.Body; FileBufferingWriteStream?fileBufferingWriteStream = null; if (!_mvcOptions.SuppressOutputFormatterBuffering) { fileBufferingWriteStream = new FileBufferingWriteStream(_jsonOptions.OutputFormatterMemoryBufferThreshold); responseStream = fileBufferingWriteStream; } var value = context.Object; if (value is not null && _asyncEnumerableReaderFactory.TryGetReader(value.GetType(), out var reader)) { var logger = context.HttpContext.RequestServices.GetRequiredService <ILogger <NewtonsoftJsonOutputFormatter> >(); Log.BufferingAsyncEnumerable(logger, value); try { value = await reader(value, context.HttpContext.RequestAborted); } catch (OperationCanceledException) { } if (context.HttpContext.RequestAborted.IsCancellationRequested) { return; } } try { await using (var writer = context.WriterFactory(responseStream, selectedEncoding)) { using var jsonWriter = CreateJsonWriter(writer); var jsonSerializer = CreateJsonSerializer(context); jsonSerializer.Serialize(jsonWriter, value); } if (fileBufferingWriteStream != null) { response.ContentLength = fileBufferingWriteStream.Length; await fileBufferingWriteStream.DrainBufferAsync(response.BodyWriter); } } finally { if (fileBufferingWriteStream != null) { await fileBufferingWriteStream.DisposeAsync(); } } }
public async override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { try { var enconding = base.SelectCharacterEncoding(context); var settings = new XmlWriterSettings(); settings.Encoding = enconding; settings.Async = true; var response = context.HttpContext.Response; var xmlWriter = CreateXmlWriter(context, new StreamWriter(response.Body), settings); var resource = context.Object as Resource; // var html = new TagBuilder("html"); html.Attributes.Add("lang", "pt-br"); // var head = new TagBuilder("head"); html.InnerHtml.AppendHtml(head); // var meta1 = new TagBuilder("meta"); head.InnerHtml.AppendHtml(meta1); meta1.Attributes.Add("charset", "utf-8"); // var meta2 = new TagBuilder("meta"); head.InnerHtml.AppendHtml(meta2); meta2.Attributes.Add("name", "viewport"); meta2.Attributes.Add("content", "width=device-width, initial-scale=1.0"); // var title = new TagBuilder("title"); head.InnerHtml.AppendHtml(title); title.InnerHtml.Append(resource.Title); // var link1 = new TagBuilder("link"); head.InnerHtml.AppendHtml(link1); link1.Attributes.Add("rel", "stylesheet"); link1.Attributes.Add("href", "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css"); // var link2 = new TagBuilder("link"); head.InnerHtml.AppendHtml(link2); link2.Attributes.Add("rel", "stylesheet"); link2.Attributes.Add("href", "/css/api.css"); // var body = new TagBuilder("body"); html.InnerHtml.AppendHtml(body); body.AddCssClass("ui basic segment"); // var div = new TagBuilder("div"); body.InnerHtml.AppendHtml(div); div.AddCssClass("ui menu"); //div.Attributes.Add("href", resource.HRef); SerializeResource(div, resource); // var resourceType = resource.GetType(); if (resourceType.IsGenericType && resourceType.GetGenericTypeDefinition() == typeof(ResourceCollection <>)) { var data = resourceType.GetProperty("Data").GetValue(resource, null) as IEnumerable; var dataItemType = resourceType.GetGenericArguments()[0]; var table = new TagBuilder("table"); body.InnerHtml.AppendHtml(table); table.AddCssClass("ui striped table"); table.Attributes.Add("href", resource.HRef); var thead = new TagBuilder("thead"); table.InnerHtml.AppendHtml(thead); var itemProperties = dataItemType.GetProperties(); var tr = new TagBuilder("tr"); thead.InnerHtml.AppendHtml(tr); foreach (var itemProperty in itemProperties) { if (itemProperty.PropertyType.IsArray || itemProperty.PropertyType.IsGenericType) { continue; } var infrastructureAttribute = itemProperty.GetCustomAttributes().FirstOrDefault(p => p.GetType() == typeof(InfrastructureAttribute)) as InfrastructureAttribute; if (infrastructureAttribute != default(InfrastructureAttribute)) { continue; } var th = new TagBuilder("th"); tr.InnerHtml.AppendHtml(th); th.AddCssClass(itemProperty.Name); var descriptionAttribute = itemProperty.GetCustomAttributes().FirstOrDefault(p => p.GetType() == typeof(DescriptionAttribute)) as DescriptionAttribute; if (descriptionAttribute == default(DescriptionAttribute)) { th.InnerHtml.AppendHtml(itemProperty.Name); } else { th.InnerHtml.AppendHtml(descriptionAttribute.Description); } } var thActions = new TagBuilder("th"); tr.InnerHtml.AppendHtml(thActions); thActions.InnerHtml.Append("Ações"); foreach (Resource innerResource in data) { SerializeResourceCollection(table, innerResource, dataItemType); } } else if (resourceType.IsGenericType && resourceType.GetGenericTypeDefinition() == typeof(ResourceForm <>)) { var action = resourceType.GetProperty("Action").GetValue(resource, null).ToString(); var method = resourceType.GetProperty("Method").GetValue(resource, null).ToString(); var data = resourceType.GetProperty("Data").GetValue(resource, null); var dataType = resourceType.GetGenericArguments()[0]; var form = new TagBuilder("form"); body.InnerHtml.AppendHtml(form); form.AddCssClass("ui form"); //form.Attributes.Add("href", resource.HRef); form.Attributes.Add("method", method); form.Attributes.Add("action", action); SerializeResourceForm(form, resource, data, dataType); var submit = new TagBuilder("input"); form.InnerHtml.AppendHtml(submit); submit.AddCssClass("ui button"); submit.Attributes.Add("type", "submit"); submit.Attributes.Add("value", "Submeter"); } else if (resourceType.IsGenericType && resourceType.GetGenericTypeDefinition() == typeof(Resource <>)) { var data = resourceType.GetProperty("Data").GetValue(resource, null); var dataType = resourceType.GetGenericArguments()[0]; var list = new TagBuilder("div"); body.InnerHtml.AppendHtml(list); list.AddCssClass("ui list"); //list.Attributes.Add("href", resource.HRef); SerializeResource(list, resource, data, dataType); } // var stringWriter = new StringWriter(); html.WriteTo(stringWriter, HtmlEncoder.Default); await xmlWriter.WriteRawAsync(stringWriter.ToString()); // await xmlWriter.FlushAsync(); xmlWriter.Close(); } catch (Exception ex) { var _ = ex.Message; throw; } }