【问题标题】:ApiController to return JSON string as-isApiController 按原样返回 JSON 字符串
【发布时间】:2014-06-07 07:42:43
【问题描述】:

我在ApiController 中有一个函数,它应该输出某种对象。该函数以已经序列化的格式接收该对象。为了让函数最终返回有效的 JSON,我需要将其转换为 JObject,如下所示:

    [HttpGet]
    public object MyFunction()
    {
        string result = .......;
        return JObject.Parse(result);
    }

问题是:结果已经是一个有效的 JSON,我想按原样返回它,无需任何处理。如果我的班级是普通的Controller,我可以只返回一个ContentResult,但由于某些原因,在这种情况下我不能将ApiController 变成普通的Controller

还有其他选择吗?

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-4


【解决方案1】:

如果操作返回System.Net.Http.HttpResponseMessage,ASP.NET Web API 将使用 HttpResponseMessage 对象的属性来填充响应,将返回值直接转换为 HTTP 响应消息。

此选项可让您对响应消息进行大量控制。

返回原始 json 的示例用法: (参考https://stackoverflow.com/a/17097919/368552

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

【讨论】:

  • 我想知道为什么他们不允许我们像在 MVC 中那样使用 ContentResult 和 Content(myString, "application/json") ...
猜你喜欢
  • 2012-12-12
  • 2013-11-29
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 2018-08-26
相关资源
最近更新 更多