Skip to content

Instantly share code, notes, and snippets.

@rodion-m
Created April 7, 2022 22:01
Show Gist options
  • Save rodion-m/97d24ab59b757daf8d8966bca25afa84 to your computer and use it in GitHub Desktop.
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).
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);
}
}
using Microsoft.AspNetCore.Mvc;
namespace Middlewares;
public class UnauthorizedResponseModelMiddleware
{
private readonly RequestDelegate _next;
private readonly ResponseDefaultFormatterService _formatterService;
public UnauthorizedResponseModelMiddleware(
RequestDelegate next,
ResponseDefaultFormatterService formatterService)
{
_next = next;
_formatterService = formatterService;
}
public async Task InvokeAsync(HttpContext context)
{
await _next(context);
if (context.Response.StatusCode == StatusCodes.Status401Unauthorized)
{
var result = new UnauthorizedObjectResult(new { Message = "Unauthorized", Code = 401 });
await _formatterService.WriteAsync(context, result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment