如何从MVC WEB API Controller返回JSON

use*_*812 8 asp.net-mvc asp.net-mvc-4

据我所知,WEB API使用Accept-Content-Type的内容协商来返回json或xml.这还不够好,我需要能够务实地决定是否要返回json或xml.

互联网充斥着过时的使用示例,HttpResponseMessage<T>MVC 4中不再存在这种示例.

    tokenResponse response = new tokenResponse();
response.something = "gfhgfh";

    if(json)
    {
        return Request.CreateResponse(HttpStatusCode.OK, response, "application/json");
    }
    else
    {
         return Request.CreateResponse(HttpStatusCode.OK, response, "application/xml");
    }
Run Code Online (Sandbox Code Playgroud)

如何更改上述代码以使其有效?

Dar*_*rov 23

试试这样:

public HttpResponseMessage Get()
{
    tokenResponse response = new tokenResponse();
    response.something = "gfhgfh";

    if(json)
    {
        return Request.CreateResponse(HttpStatusCode.OK, response, Configuration.Formatters.JsonFormatter);
    }
    else
    {
         return Request.CreateResponse(HttpStatusCode.OK, response, Configuration.Formatters.XmlFormatter);
    }    
}
Run Code Online (Sandbox Code Playgroud)

或者甚至更好,为了避免使用这样的管道基础设施代码使控制器混乱,您还可以编写自定义媒体格式化程序并在其中执行此测试.