本文介绍了返回“原始" 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字符串的获取方式无关紧要,它可以来自第三方服务,也可以有一些特殊的序列化需求,因此我们希望自定义序列化而不是使用默认的JSON .NET序列化程序.

推荐答案

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

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

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:20