asp.net-mvc 如何从 MVC WEB API 控制器返回 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12705276/
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-08 02:19:04  来源:igfitidea点击:

How to return JSON from MVC WEB API Controller

asp.net-mvcasp.net-mvc-4

提问by user1662812

I understand that WEB API uses content negotiation for Accept - Content-Type to return json or xml. This is not good enough and I need to be able pragmatically decide if I want to return json or xml.

我了解 WEB API 使用内容协商接受 - Content-Type 返回 json 或 xml。这还不够好,我需要能够务实地决定是要返回 json 还是 xml。

The internet is flooded with obsolete examples of using HttpResponseMessage<T>, which is no longer present in MVC 4.

互联网上充斥着过时的 using 示例,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");
    }

How do I change the above code so that it works?

如何更改上面的代码以使其正常工作?

回答by Darin Dimitrov

Try like this:

像这样尝试:

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

or even better, to avoid cluttering your controller with such plumbing infrastructure code you could also write a custom media formatter and perform this test inside it.

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