据我所知,WEB API使用Accept-Content-Type的内容协商来返回json或xml.
这还不够好,我需要能够务实地决定是否要返回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,"application/xml"); }
如何更改上述代码以使其有效?
解决方法
试试这样:
public HttpResponseMessage Get() { tokenResponse response = new tokenResponse(); response.something = "gfhgfh"; if(json) { return Request.CreateResponse(HttpStatusCode.OK,Configuration.Formatters.JsonFormatter); } else { return Request.CreateResponse(HttpStatusCode.OK,Configuration.Formatters.XmlFormatter); } }