如何通过Asp.Net Core中间件的JsonResult做出响应? [英] How to respond via an JsonResult from Asp.Net Core middleware?

查看:478
本文介绍了如何通过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);
}

这篇关于如何通过Asp.Net Core中间件的JsonResult做出响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆