2012-10-03 49 views
8

我知道WEB API使用Accept-Content-Type的內容協商來返回json或xml。 這不夠好,我需要能夠務實地決定是否要返回json或xml。如何從MVC WEB API控制器返回JSON

互聯網上充斥着使用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"); 
    } 

如何更改上面的代碼,以便它的工作原理?

回答

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

,甚至更好,以避免與這樣的管道基礎設施代碼弄亂你的控制器也可以寫一個自定義的媒體格式,並在其內部進行測試。

+0

對!我的錯誤是Get()方法有一個返回類型的tokenResponse。謝謝! – user1662812