Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the default serializer in ASP.NET Web API?

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.

like image 806
Michael Schnerring Avatar asked Oct 16 '12 15:10

Michael Schnerring


People also ask

What is JSON serialization in Web API?

Serialization and deserialization in . NET application, JSON data format conversion to . NET objects and vice versa is very common. Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects.

Which library does Web API use for JSON Serialisation?

JSON Media-Type Formatter By default, JsonMediaTypeFormatter uses the Json.NET library to perform serialization. Json.NET is a third-party open source project.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


1 Answers

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).

like image 126
James Avatar answered Oct 25 '22 00:10

James