【问题标题】:How to return JSON from MVC WEB API Controller如何从 MVC WEB API 控制器返回 JSON
【发布时间】:2012-10-03 09:11:24
【问题描述】:

我了解 WEB API 使用内容协商来接受 - 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");
    }

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

【问题讨论】:

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


    【解决方案1】:

    试试这样:

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

    甚至更好的是,为了避免让你的控制器被这样的管道基础设施代码弄乱,你还可以编写一个自定义媒体格式化程序并在其中执行这个测试。

    【讨论】:

    • 对!我的错误是 Get() 方法的返回类型为 tokenResponse。谢谢!
    • 在这个例子中任何可以替代 tokenResponse 的标准类?
    猜你喜欢
    • 2013-04-30
    • 1970-01-01
    • 2016-03-22
    • 2017-05-18
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多