title: What is the best way to serialize the response to JSON inside middleware?
body: <p>Is there a canonical way to leverage the configured <code>JsonOutputFormatter</code> inside ASP.NET middleware? Or, more generically, is there a better way to serialize the response to JSON than explicitly calling <code>JsonConvert.SerializeObject</code> in my middleware?</p>
  
  <p>Currently, I have the following code:</p>
  
  <pre><code>public static void HandleHealthRequests(this IApplicationBuilder app)
  {
      app.Map(new PathString("/health"), builder =&gt;
      {
          builder.Run(async context =&gt;
          {
              string response = JsonConvert.SerializeObject(new { DateTime.UtcNow, Version = _version });
              context.Response.StatusCode = StatusCodes.Status200OK;
              context.Response.ContentType = "application/json";
              context.Response.ContentLength = response.Length;
              await context.Response.WriteAsync(response);
          });
      });
  }
  </code></pre>
  
  <p>This works fine, but calling <code>JsonConvert.SerializeObject</code> directly and manipulating the <code>Response</code> directly doesn't feel right.</p>
  
  <p>I looked at resolving the <code>JsonOutputFormatter</code> to leverage it directly but it requires an <code>OutputFormatterContext</code> which looks too complicated to set up. Additionally, I also tried just leveraging <code>JsonOutputFormatter.SerializerSettings</code> but found it to be <code>null</code> on app startup so my code was throwing when the process started. </p>