I would like to respond via a JsonResult
from a piece of Asp.Net Core middleware but it's not obvious how to accomplish that. I have googled around alot but with little success. I can respond via a JsonResult
from a global IActionFilter
by setting the ActionExecutedContext.Result
to the JsonResult
and that's cool. But in this case I want to effectively return a JsonResult
from my middleware. How can that be accomplished?
I framed the question with regard to the JsonResult
IActionResult
but ideally the solution would work for using any IActionResult
to write the response from the 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
.