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

klu*_*msy 83 asp.net-mvc json asp.net-web-api

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

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

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

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

car*_*ira 191

还有一些选择.最简单的方法是让你的方法返回一个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;
}
Run Code Online (Sandbox Code Playgroud)

并检查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);
}
Run Code Online (Sandbox Code Playgroud)

  • 优秀.我正在制作一个JSON字符串并将其作为字符串返回,但这导致了不可避免的额外"围绕结果.这应该解决这个问题. (4认同)

tym*_*tam 13

这在 .NET Core 3.1 中适用于我。

private async Task<ContentResult> ChannelCosmicRaysAsync(HttpRequestMessage request)
{
    // client is HttpClient
    using var response = await client.SendAsync(request).ConfigureAwait(false); 

    var responseContentString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

    Response.StatusCode = (int)response.StatusCode;
    return Content(responseContentString, "application/json");
}
Run Code Online (Sandbox Code Playgroud)
public Task<ContentResult> X()
{
    var request = new HttpRequestMessage(HttpMethod.Post, url);
    (...)

    return ChannelCosmicRaysAsync(request);
}
Run Code Online (Sandbox Code Playgroud)

ContentResultMicrosoft.AspNetCore.Mvc.ContentResult

请注意,这不是频道标题,但就我而言,这就是我所需要的。


Jps*_*psy 8

这是@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);
}
Run Code Online (Sandbox Code Playgroud)


小智 8

从 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\");
}
Run Code Online (Sandbox Code Playgroud)

  • 内容从哪里来?完全限定的名称或“using”声明会很有帮助。 (4认同)