ASP.NET 5 RC1 Web API always returns JSON – Why ?


Hello All,

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

  1. Added Microsoft.AspNet.Mvc as dependency in project.json.
  2. In ConfigureServices method of startup.cs, added services.AddMvc()
  3. In Configure method of startup.cs, added app.UseMvc();
  4. Added a Controllers folder in solution and added a controller class with name as PeopleController which inherits from Controller.
  5. Added the attribute route on the controller as
  6. 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

request

I get the response in JSON format

response

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

acceptrequest

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.

https://github.com/aspnet/Mvc/issues/1765

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

  1. Microsoft.AspNet.Mvc.Formatters.Xml
  2. Microsoft.AspNet.Mvc.Formatters.Json

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();
    mvcBuilder.AddXmlDataContractSerializerFormatters();
}

Now when I ran the package with Accept header as text/xml, it return the response in XML format as

xmlresponse

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.

Cheers
Brij

 

Advertisement