在某些情况下,我有NewtonSoft JSON.NET,在我的控制器中,我从控制器返回Jobject,一切都很好.

但是我有一个 case ,我从另一个服务获得一些原始JSON,并且需要从我的webAPI返回它.在这种情况下,我不能使用NewtonSOft,但如果可以的话,我会从字符串创建一个JOBJECT(这似乎是不需要的处理开销),然后返回它,这样一切都会很顺利.

However, I want to return this simply, but if I return the string, then the client receives a JSON wrapper with my context as an encoded string.

如何从WebAPI控制器方法显式返回JSON?

推荐答案

有几种 Select .最简单的方法是让方法返回HttpResponseMessage,然后根据字符串创建StringContent响应,类似于下面的代码:

public HttpResponseMessage Get()
{
    string yourJson = GetJsonFromSomewhere();
    var response = this.Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json");
    return response;
}

And checking null or empty JSON string

public HttpResponseMessage Get()
{
    string yourJson = GetJsonFromSomewhere();
    if (!string.IsNullOrEmpty(yourJson))
    {
        var response = this.Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json");
        return response;
    }
    throw new HttpResponseException(HttpStatusCode.NotFound);
}

Json相关问答推荐

try 将文本标记放置在条形图上的同一高度

Vega通孔信号中的动态梯度

从json数组中删除特定元素

如何编写MongoDB查询以返回数组数组

将数组中的值作为键连接到另一个数组中的值(Jolt)

JOLT转换以基于对象属性过滤JSON数组

如何将属性拆分为嵌套的JSON内容?

如何在jolt中使用shift和modify-overwrite-beta

JSON 字段的多个名称

从 JSON 响应中获取最新版本发布字段

Microsoft GRAPH 查询使用端点 /deviceManagement/deviceHealthScripts 列出了一种不熟悉的检测脚本内容格式

JSON Schema 与 XML Schema 的比较及其future

python,将Json写入文件

IE8 原生 JSON.parse 错误导致堆栈溢出

验证和格式化 JSON 文件

如何将 LinkedTreeMap 转换为 gson JsonObject

使用 API 搜索维基百科

如何创建 JSON 对象 Node.js

XML vs YAML vs JSON

无法解析 JSON 文件中的 TAB