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.
To return data in a specific format from a controller that inherits from the Controller base class, use the built-in helper method Json to return JSON and Content for plain text. Your action method should return either the specific result type (for instance, JsonResult ) or IActionResult .
JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format).
Middleware in ASP.NET Core controls how our application responds to HTTP requests. It can also control how our application looks when there is an error, and it is a key piece in how we authenticate and authorize a user to perform specific actions.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With