简体   繁体   中英

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:

  • User should specify return type with a parameter.
  • 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?

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提琴手的请求和响应

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提琴手响应请求

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); }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM