Note – For this example, I am have used Visual Studio 2015 Update 1 for IDE and ASP.NET 5 RC1.
Recently I started working on an ASP.NET Web API application but I got stuck at one point for few hours. Let’s start from scratch and create the application first then we will see the behavior and various options. As I (most of us) like to start from clean slate so I created an empty ASP.NET application and followed the below stuff
- Added Microsoft.AspNet.Mvc as dependency in project.json.
- In ConfigureServices method of startup.cs, added services.AddMvc()
- In Configure method of startup.cs, added app.UseMvc();
- Added a Controllers folder in solution and added a controller class with name as PeopleController which inherits from Controller.
- Added the attribute route on the controller as
- Now we have done all the necessary set up and added a Controller for Web API. I have added a DataHelper class in Models folder (which I added) which returns a list of persons.
Now when I run that application and call the API using Fiddler as
I get the response in JSON format
Although we didn’t send any Accept header in request. It means now the default response format is JSON only. Now I added the Accept header as
Then also the response was same as earlier.
As per earlier understanding that the returned content type should be as per the Accept header which is not the case when I did some research, I found that now by default only JSON formatter is included. Refer the below link for detailed discussion.
And this was implemented in beta 3 release and it says that to add the XML formatter, we need to include the package Microsoft.AspNet.Mvc.Xml but I got an error while including this package because the latest version available is beta5 and the version of MVC we are using is rc1. After spending few hours, I discovered that the package Microsoft.AspNet.Mvc.Xml is not the correct one now and there was no update in it since 30th Jun’15. Two new packages for formatting XML and JSON format got introduced as
Currently there is no details available on earlier package that now some new packages are available instead of Microsoft.AspNet.Mvc.Xml which made it bit tough to find the right one.
As we realized, JSON is included by default with MVC package, I added Xml package and configureed it in services as
public void ConfigureServices(IServiceCollection services)
var mvcBuilder = services.AddMvc();
Now when I ran the package with Accept header as text/xml, it return the response in XML format as
But default is JSON only so we don’t need to send any information in header if we just want the result in JSON format.