Created
April 7, 2022 22:01
-
-
Save rodion-m/97d24ab59b757daf8d8966bca25afa84 to your computer and use it in GitHub Desktop.
Here is a solution that allows to write ObjectResult inside Middleware (write http response using MVC formatters (serializers) from Middleware).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.AspNetCore.Mvc.Formatters; | |
using Microsoft.AspNetCore.Mvc.Infrastructure; | |
namespace Services; | |
public class ResponseDefaultFormatterService | |
{ | |
private readonly IHttpResponseStreamWriterFactory _streamWriterFactory; | |
private readonly OutputFormatterSelector _formatterSelector; | |
public ResponseDefaultFormatterService( | |
IHttpResponseStreamWriterFactory streamWriterFactory, | |
OutputFormatterSelector formatterSelector) | |
{ | |
_streamWriterFactory = streamWriterFactory; | |
_formatterSelector = formatterSelector; | |
} | |
public async Task WriteAsync(HttpContext context, ObjectResult result) | |
{ | |
var formatterContext = new OutputFormatterWriteContext( | |
context, | |
_streamWriterFactory.CreateWriter, | |
result.DeclaredType ?? result.Value?.GetType(), | |
result.Value); | |
var selectedFormatter = _formatterSelector.SelectFormatter( | |
formatterContext, | |
(IList<IOutputFormatter>)result.Formatters ?? Array.Empty<IOutputFormatter>(), | |
result.ContentTypes); | |
if (selectedFormatter == null) | |
{ | |
context.Response.StatusCode = StatusCodes.Status406NotAcceptable; | |
return; | |
} | |
await selectedFormatter.WriteAsync(formatterContext); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment