title: How can I return a response in ASP.NET Core MVC middleware using MVC's content negotiation?
body: <p>I have some ASP.NET Core MVC middleware to catch unhandled exceptions that I would like to return a response from.</p>
  
  <p>While it is easy to just <code>httpContext.Response.WriteAsync</code> to write a string and e.g. use <code>JsonSerializer</code> to serialise an object to a string, I would like to use the standard serialisation settings and content negotiation so that if I change my default output formatting to XML or a <code>text/xml</code> accept header is sent when I have multiple output formatters configured then XML is returned, as it does if I return an <code>ObjectResult</code> from a controller.</p>
  
  <p>Does anyone know how this can be achieved in middleware?</p>
  
  <p>Here is my code so far which only writes JSON:</p>
  
  <pre><code>public class UnhandledExceptionMiddleware
  {
      private readonly RequestDelegate _next;
      private readonly IOutputFormatter _outputFormatter;
      private readonly IHttpResponseStreamWriterFactory _streamWriterFactory;
  
      public UnhandledExceptionMiddleware(RequestDelegate next, JsonOutputFormatter outputFormatter, IHttpResponseStreamWriterFactory streamWriterFactory)
      {
          _next = next;
          _outputFormatter = outputFormatter;
          _streamWriterFactory = streamWriterFactory;
      }
  
      public async Task Invoke(HttpContext context)
      {
          try
          {
              await _next(context);
          }
          catch (Exception ex)
          {
              await HandleExceptionAsync(context, ex);
          }
      }
  
      private async Task HandleExceptionAsync(HttpContext context, Exception exception)
      {
          var error = new ErrorResultModel("Internal Server Error", exception.Message, exception.StackTrace);
          context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
          await _outputFormatter.WriteAsync(new OutputFormatterWriteContext(context, _streamWriterFactory.CreateWriter, typeof(ErrorResultModel), error));
      }
  }
  </code></pre>
  
  <p>where <code>ErrorResultModel</code> is defined as:</p>
  
  <pre><code>public class ErrorResultModel
  {
      public string ResultMessage { get; };
      public string ExceptionMessage { get; };
      public string ExceptionStackTrace { get; };
  
      public ErrorResultModel(string resultMessage, string exceptionMessage, string exceptionStackTrace)
      {
          ResultMessage = resultMessage;
          ExceptionMessage = exceptionMessage;
          ExceptionStackTrace = exceptionStackTrace;
      }
  }
  </code></pre>