Tuesday 22 September 2015

Web API 2 : Convert default xml media type to json

Even if we specify a Web API call to return a json type, when we navigate tothe api call usign a browser, it returns an xml formatted data.

 
             var expenseGroups = _repository.GetExpenseGroups();

             return Ok(expenseGroups.ToList()
                    .Select(eg => _expenseGroupFactory.CreateExpenseGroup(eg)));

But we would get a result something as follows in the browser.

This happens because the browser request for the text/html type in its request header
Example browser request header
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
We can program our API in way that , if browser request for a text format the request to json.
Following is the formatting code we need to get done in the WebApiConfig
 
             var expenseGroups = _repository.GetExpenseGroups();

             return Ok(expenseGroups.ToList()
                    .Select(eg =gt; _expenseGroupFactory.CreateExpenseGroup(eg)));

We can get the following result.

No comments:

Post a Comment