从 Asp.net WEBAPI 显式返回 JSON 字符串? [英] Return a JSON string explicitly from Asp.net WEBAPI?

查看:37
本文介绍了从 Asp.net WEBAPI 显式返回 JSON 字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Some cases I have NewtonSoft JSON.NET and in my controller I just return the Jobject from my controller and all is good.

但我有一个案例,我从另一个服务获取了一些原始 JSON,并且需要从我的 webAPI 返回它.在这种情况下,我不能使用 NewtonSOft,但如果可以的话,我会从字符串创建一个 JOBJECT(这似乎是不需要的处理开销)并返回它,一切都会好起来的.

But I have a case where I get some raw JSON from another service and need to return it from my webAPI. In this context I can't use NewtonSOft, but if I could then I'd create a JOBJECT from the string (which seems like unneeded processing overhead) and return that and all would be well with the world.

但是,我想简单地返回它,但是如果我返回字符串,那么客户端会收到一个 JSON 包装器,其中包含我的上下文作为编码字符串.

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?

How can I explicitly return a JSON from my WebAPI controller method?

推荐答案

有几个替代方案.最简单的方法是让您的方法返回一个 HttpResponseMessage,然后使用基于您的字符串的 StringContent 创建该响应,类似于下面的代码:

There are a few alternatives. The simplest one is to have your method return a HttpResponseMessage, and create that response with a StringContent based on your string, something similar to the code below:

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

并检查 null 或空的 JSON 字符串

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);
}

这篇关于从 Asp.net WEBAPI 显式返回 JSON 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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