How to respond through JsonResult from Asp.Net Core middleware?

I would like to answer via JsonResult from the Asp.Net Core middleware part, but it is not obvious how to do this. I walked a lot, but with little success. I can respond via JsonResult from the global IActionFilter by setting ActionExecutedContext.Result to JsonResult and this is cool. But in this case, I want to effectively return JsonResult from my middleware. How can I do that?

I formulated a question regarding the JsonResult IActionResult , but ideally the solution would work to use any IActionResult to record the response from the middleware.

+5
source share
2 answers

Middleware is a truly low-level component of ASP.NET Core. JSON writing (efficiently) is implemented in the MVC repository. In particular, in the JSON formatters component.

It basically comes down to writing JSON in the response stream. In its simplest form, it can be implemented in middleware as follows:

 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); } 
+6
source

For others who might be wondering how to return JsonResult output 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 JsonResult , and the approach is close to being able to include middleware to return output from any IActionResult. To handle this more general case, the code for creating an ActionDescriptor will need to be improved. But doing this up to this point was enough for my needs to return JsonResult output.

+1
source

Source: https://habr.com/ru/post/1266095/


All Articles