2015-02-06 52 views
1

Asp.net的默认返回类型是XML。但我可以在配置设置中改变它。asp.net web api用户选择的内容类型

public static void Register(HttpConfiguration config) 
{ 
    config.Formatters.Clear(); 
    // config.Formatters.Add(new XmlMediaTypeFormatter()); 
    config.Formatters.Add(new JsonMediaTypeFormatter()); 
} 

我的控制器:

public class ProductController: ApiController 
{ 
    public IEnumerable<Product> Get() 
    { 
     return new List<Product> { 
      new Product {Name = "p1", Price = 10}, 
      new Product {Name = "p2", Price = 20} 
     }; 
    } 
} 

现在我想这样的:

  • 用户应该用参数指定返回类型。
  • http://domain/product/get(格式XML或JSON)

我不想改变我的控制器操作。

有没有办法用Route参数或任何其他级别来做到这一点?

回答

1

默认情况下,如果没有指定格式化程序,web api将返回xml或json。

如果需要返回JSON你只需指定从客户端下面的标题:

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

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