从 Asp.net WEBAPI 显式返回 JSON 字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17097841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:51:42  来源:igfitidea点击:

Return a JSON string explicitly from Asp.net WEBAPI?

asp.net-mvcjsonasp.net-web-api

提问by klumsy

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

在某些情况下,我有 NewtonSoft JSON.NET,在我的控制器中,我只是从我的控制器返回 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 并需要从我的 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.

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

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

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

回答by carlosfigueira

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

有几种选择。最简单的方法是让您的方法返回 a HttpResponseMessage,并StringContent根据您的字符串使用 a 创建该响应,类似于以下代码:

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

并检查 null 或空的 JSON 字符串

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

回答by Jpsy

Here is @carlosfigueira's solution adapted to use the IHttpActionResult Interface that was introduced with WebApi2:

这是@carlosfigueira 的解决方案,适用于使用 WebApi2 引入的 IHttpActionResult 接口:

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

回答by Joe Enos

If you specifically want to return that JSON only, without using WebAPI features (like allowing XML), you can always write directly to the output. Assuming you're hosting this with ASP.NET, you have access to the Responseobject, so you can write it out that way as a string, then you don't need to actually return anything from your method - you've already written the response text to the output stream.

如果您特别想仅返回该 JSON,而不使用 WebAPI 功能(例如允许 XML),您始终可以直接写入输出。假设您使用 ASP.NET 托管它,您可以访问该Response对象,因此您可以将其作为字符串写出,然后您实际上不需要从您的方法中返回任何内容 - 您已经编写了对输出流的响应文本。

回答by Muni Chittem

sample example to return json data from web api GET method

从 web api GET 方法返回 json 数据的示例示例

[HttpGet]
public IActionResult Get()
{
            return Content("{\"firstName\": \"John\",  \"lastName\": \"Doe\", \"lastUpdateTimeStamp\": \"2018-07-30T18:25:43.511Z\",  \"nextUpdateTimeStamp\": \"2018-08-30T18:25:43.511Z\");
}

回答by eci

these also work:

这些也有效:

[HttpGet]
[Route("RequestXXX")]
public ActionResult RequestXXX()
{
    string error = "";
    try{
        _session.RequestXXX();
    }
    catch(Exception e)
    {
        error = e.Message;
    }
    return new JsonResult(new { error=error, explanation="An error happened"});
}

[HttpGet]
[Route("RequestXXX")]
public ActionResult RequestXXX()
{
    string error = "";
    try{
        _session.RequestXXX();
    }
    catch(Exception e)
    {
        error = e.Message;
    }
    return new JsonResult(error);
}