【问题标题】:asp.net web api user selected content typeasp.net web api 用户选择的内容类型
【发布时间】:2015-02-06 09:17:49
【问题描述】:

Asp.net 默认返回类型是 XML。但我可以在配置设置中更改它。

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 参数或任何其他级别来做到这一点?

【问题讨论】:

    标签: c# asp.net json asp.net-mvc asp.net-web-api


    【解决方案1】:

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

    如果您需要返回 json,您只需在标头中从客户端指定以下内容:

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

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

    【讨论】:

      猜你喜欢
      • 2011-10-26
      • 2015-10-15
      • 2021-04-25
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-28
      • 2014-02-22
      相关资源
      最近更新 更多