Reputation: 6875
Asp.net default return type is XML. But I can change that in config settings.
public static void Register(HttpConfiguration config)
{
config.Formatters.Clear();
// config.Formatters.Add(new XmlMediaTypeFormatter());
config.Formatters.Add(new JsonMediaTypeFormatter());
}
My controller is:
public class ProductController: ApiController
{
public IEnumerable<Product> Get()
{
return new List<Product> {
new Product {Name = "p1", Price = 10},
new Product {Name = "p2", Price = 20}
};
}
}
Now I want to this:
http://domain/product/get
(format xml or json)I do not want to change my controller action.
Is there any way to do this with Route parameter or any other level?
Upvotes: 1
Views: 509
Reputation: 33306
By default without specifying a formatter the web api will return xml or json.
If you need to return json you simply specify the following from the client in the header:
Accept: application/json
Javascript
var urlString = "http://localhost/api/values/Get";
$.ajax({
url: urlString,
type: 'GET',
data: {id : 1},
dataType: 'json',
contentType: 'application/json',
success: function (data) { console.log(data); }
});
Or xml:
Accept: application/xml
Javascript
var urlString = "http://localhost/api/values/Get";
$.ajax({
url: urlString,
type: 'GET',
data: {id : 1},
dataType: 'xml',
contentType: 'application/xml',
success: function (data) { console.log(data); }
});
Upvotes: 1