How to respond via an JsonResult from Asp.Net Core middleware? How to respond via an JsonResult from Asp.Net Core middleware? json json

How to respond via an JsonResult from Asp.Net Core middleware?


Middleware is a really low-level component of ASP.NET Core. Writing out JSON (efficiently) is implemented in the MVC repository. Specifically, in the JSON formatters component.

It basically boils down to writing JSON on the response stream. In its simplest form, it can be implemented in middleware like this:

using Microsoft.AspNetCore.Http;using Newtonsoft.Json;// ...public async Task Invoke(HttpContext context){    var result = new SomeResultObject();    var json = JsonConvert.SerializeObject(result);    await context.Response.WriteAsync(json);}


For others that may be interested in how to return the output of a JsonResult from middleware, this is what I came up with:

  public async Task Invoke(HttpContext context, IHostingEnvironment env) {        JsonResult result = new JsonResult(new { msg = "Some example message." });        RouteData routeData = context.GetRouteData();        ActionDescriptor actionDescriptor = new ActionDescriptor();        ActionContext actionContext = new ActionContext(context, routeData, actionDescriptor);        await result.ExecuteResultAsync(actionContext);    }

This approach allows a piece of middleware to return output from a JsonResult and the approach is close to being able to enable middleware to return the output from any IActionResult. To handle that more generic case the code for creating the ActionDescriptor would need improved. But taking it to this point was sufficient for my needs of returning the output of a JsonResult.


As explained by @Henk Mollema, I have also made use of Newtonsoft.Json JsonConvert class to serialize the object into JSON through SerializeObject method. For ASP.NET Core 3.1 I have used JsonConvert inside the Run method. Following solution worked for me:

Startup.cs

using Newtonsoft.Json;// ...public class Startup{    public void Configure(IApplicationBuilder app)     {        app.Run(async context =>        {            context.Response.StatusCode = 200;            context.Response.ContentType = "application/json";            await context.Response.WriteAsync(JsonConvert.SerializeObject(new            {                message = "Yay! I am a middleware"            }));        });    }}