Web API 2返回文本/简单响应

Nic*_*oad 7 c# asp.net-mvc json asp.net-web-api2

真的很挣钱,我希望这里的人可以提供帮助.我正在写在网页API 2.一个RESTful API每当我发送给此服务的请求,响应始终都与发送Content-Typetext/plain.显然,这是不行的,我的反应必须Content-Typeapplication/json.我已经尝试了一些我从谷歌发现的建议,但我认为我并不了解整体情况.

为了让我的网络服务回复application/json内容,我需要做些什么特别的事吗?请注意,我希望这在整个应用程序中全局工作,所以我不是在修改给定的响应并设置其内容类型 - 我希望这是整个Web服务的默认行为:如果请求包含一个Accept为标题application/json我想我的web服务,以返回Content-Type代替text/plain.

编辑澄清:

我的响应包含一个名为"responseData"的对象,该对象应序列化为JSON并包含在正文中.我目前正在将这样的回答放在一起:

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, responseData);
return response;
Run Code Online (Sandbox Code Playgroud)

responseData是一个POCO.这个get被正确地序列化为JSON并在响应中返回 - 唯一缺少的部分是Content-Type,它被错误地设置为"text/plain".我可以在我编写的每个响应上手动更改它,但我想在全局级别配置它.

Cor*_*rey 9

好的,假设你responseData是一个字符串,Content-type标题将text/plain在你创建时HttpResponseMessage.无论字符串的内容是什么,因为没有尝试确定这一点.

解决方案是为您的消息创建适当的Content对象,使用您要返回的媒体类型进行初始化:

HttpResponseMessage response = new HttpResponseMessage()
    {
        Content = new StringContent(
                responseData,
                Encoding.UTF8,
                "application/json"
            )
    };
Run Code Online (Sandbox Code Playgroud)

还有其他方法相当于返回特定的对象类型,并允许API库根据需要为您序列化为JSON或XML.我更愿意让框架尽可能地为我工作,但这就是你用你自己创建的字符串来实现它的方法.


对于严格的仅JSON结果,从WebAPI配置中删除XML格式化程序并返回您的POCO.

App_Start\WebApiConfig.cs,将以下内容添加到WebApiConfig.Register方法中:

config.Formatters.Remove(config.Formatters.XmlFormatter);
Run Code Online (Sandbox Code Playgroud)

对于您的API:

public class MyObject
{
    public bool result;
    public string reason;
}

public class TestController : ApiController
{
    public MyObject GetData()
    {
        MyObject result = new MyObject { result = "true", reason = "Testing POCO return" };
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

我运行了这个并/api/Test从Chrome 请求,application/jsonAccept标题中甚至没有提到.以下是响应标题,直至达到Content-Type:

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Run Code Online (Sandbox Code Playgroud)

和身体:

{"result":true,"reason":"Testing POCO return"}
Run Code Online (Sandbox Code Playgroud)

由于我禁用了XML,因此默认为JSON.