簡體   English   中英

如何從MVC WEB API Controller返回JSON

[英]How to return JSON from MVC WEB API Controller

據我所知,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");
    }

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

試試這樣:

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

或者甚至更好,為了避免使用這樣的管道基礎設施代碼使控制器混亂,您還可以編寫自定義媒體格式化程序並在其中執行此測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM