如何通过Asp.Net Core中间件的JsonResult做出响应?
我想通过一个Asp.Net Core中间件通过JsonResult
进行响应,但如何实现这一点尚不清楚.我在很多地方用Google搜索,但收效甚微.我可以通过将ActionExecutedContext.Result
设置为JsonResult
从全局IActionFilter
通过JsonResult
进行响应,这很酷.但是在这种情况下,我想从中间件有效地返回JsonResult
.怎么能做到?
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?
我对有关JsonResult
IActionResult
的问题进行了框架化,但理想情况下,该解决方案适用于使用任何IActionResult
编写来自中间件的响应.
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.
中间件是ASP.NET Core的真正底层组件.在MVC存储库中实现了有效写出JSON的功能.具体来说,在 JSON格式器组件中
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.
基本上可以归结为在响应流上编写JSON.以最简单的形式,它可以在这样的中间件中实现:
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);
}