如何通过Asp.Net Core中间件的JsonResult做出响应?

编程入门 行业动态 更新时间:2024-10-25 00:37:02
本文介绍了如何通过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做出响应?

本文发布于:2023-11-05 09:49:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560516.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中间件   Net   Asp   JsonResult   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!