barteloma
barteloma

Reputation: 6875

asp.net web api user selected content type

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:

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

Answers (1)

hutchonoid
hutchonoid

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

json fiddler request and response

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

xml fiddler response request

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

Related Questions