开发者

Returning XML or JSON depending on the HTTP request

I am trying to develop a RESTful Web service as an ASP.NET MVC 3 Web Application.

(I know, I should use th开发者_JS百科e right tool for the job, which in this case means I should use WCF. But WCF has too many abstraction layers and is thus too big to fit inside my head. It would be cool for a research project, but I am trying to do my job. Besides I previously tried it, and now I am of the opinion that, despite its big promises, WCF sucks big time.)

Anyway, what I want to do is simple: I want my Web service to return its results as either XML or JSON, depending on the type specified in the HTTP request (by, default, JSON). How do I do that?


A Json action result already exists. MvcContrib has an XML action result you can return, or you could just use Content (xmlContent, "text/xml") as your action result.

You can query the accept header to determine which action result you would like to return. As long as your action method returns type ActionResult, it doesn't matter which type it returns.

That said, once you prove the overall concept, there are better ways to structure what you're trying to do.


A quick solution is to create an optional parameter on your Controller method, and return the view as the appropriate format.

public ActionResult GetFormattedResults(string format)
{
   var data = GetResults();

   ActionResult result = new JsonResult(data);

   switch(format.ToLower())
   {
     case "xml":
        result = new XmlResult(data); // this class doesn't exist in MVC3 you will need to roll your own
     case "html":
        result = new View(data);
   }

   return result;
}

You could also wrap the formatting functionality into an ActionFilter so you can reuse the functionality across controller methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜