Reputation: 3661
I'm currently watching a video course about ASP.NET Web API. When a controller gets called, the data gets returned in JSON by default. I was just wondering, because when I copy this sample project from the video, I get XML.
The frustration is big, please help me to solve this.
I'm pretty new to ASP.NET Web API, so please bear with me.
UPDATE
The controller doesn't contain special code. It's the simple code, which gets generated from the API Controller with empty read/write actions template.
Upvotes: 14
Views: 8193
Reputation: 366
James is close, but the content negotiation actually uses the [Accept] header, not [Content-Type]
As with nearly everything else in MVC, you can override the content negotiation components to ensure the desire content is returned
W3c clearly states-
14.1 Accept
The Accept request-header field can be used to specify certain media types which are acceptable for the response.
-and-
14.17 Content-Type
The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
This page headers is very useful to understand request/response negotiation.
Upvotes: 5
Reputation: 82136
ASP.NET WebAPI comes with built-in content negotitation therefore the format of the return value is determined by the request itself - more specifically by the Accept
/Content-Type
headers (depending on which ones are present, Accept
header appears to be favoured over the Content-type
).
I assume you're viewing the results in a browser and by default it's probably asking for application/xml
. You will need to toy around with some settings/developer tools on the browser and force it to send Content-Type: application/json
to get the correct response (assuming your returning HttpResponseMessage).
Upvotes: 10
Reputation: 3665
in Global.asax: add the line:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
It'll look like this.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}
Upvotes: 8