返回“原始"ASP.NET Core 2.0 Web Api 中的 json

编程入门 行业动态 更新时间:2024-10-18 16:52:35
本文介绍了返回“原始"ASP.NET Core 2.0 Web Api 中的 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

AFAIK 在 ASP.NET Core Web Api 中返回数据的标准方式是使用 IActionResult 并提供例如OkObject 结果.这适用于对象,但是如果我以某种方式获得了一个 JSON 字符串,而我只想将该 JSON 返回给调用者呢?

The standard way AFAIK to return data in ASP.NET Core Web Api is by using IActionResult and providing e.g. an OkObject result. This works fine with objects, but what if I have obtained a JSON string somehow, and I just want to return that JSON back to the caller?

例如

public IActionResult GetSomeJSON() { return Ok("{ "name":"John", "age":31, "city":"New York" }"); }

ASP.NET Core 在这里所做的是,它接受 JSON 字符串,并将其再次包装成 JSON(例如,它转义 JSON)

What ASP.NET Core does here is, it takes the JSON String, and wraps it into JSON again (e.g. it escapes the JSON)

使用 [Produces("text/plain")] 返回纯文本确实通过提供RAW"内容来工作,但它还将响应的内容类型设置为 PLAIN 而不是 JSON.我们在控制器上使用 [Produces("application/json")].

Returning plain text with [Produces("text/plain")] does work by providing the "RAW" content, but it also sets the content-type of the response to PLAIN instead of JSON. We use [Produces("application/json")] on our Controllers.

如何在不转义的情况下将我拥有的 JSON 作为普通 JSON 内容类型返回?

How can I return the JSON that I have as a normal JSON content-type without it being escaped?

注意:JSON 字符串的获取方式无关紧要,它可能来自 3rd 方服务,或者有一些特殊的序列化需求,因此我们想要进行自定义序列化而不是使用默认的 JSON.NET 序列化程序.

推荐答案

当然,在发布问题几分钟后,我偶然发现了一个解决方案 :)

And of course a few minutes after posting the question I stumble upon a solution :)

只需返回内容类型为 application/json...

Just return Content with the content type application/json...

return Content("{ "name":"John", "age":31, "city":"New York" }", "application/json");

更多推荐

返回“原始"ASP.NET Core 2.0 Web Api 中的 json

本文发布于:2023-11-13 15:10:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584668.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原始   ASP   NET   Core   quot

发布评论

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

>www.elefans.com

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