为什么asp.net webAPI总是返回text / html?

时间:2016-09-05 09:37:20

标签: asp.net-web-api

我想创建返回json的webservices。但是,我总是得到&text; / html'作为回复内容类型。

第一枪:

 public StringContent Get()
 {
     List<Cell> list = new List<Cell>();
     Cell c = new Cell("Cell1");
     Cell c2 = new Cell("Cell2");
     list.Add(c);
     list.Add(c2);

     return new StringContent(
       Newtonsoft.Json.JsonConvert.SerializeObject(list),
       Encoding.UTF8,
       "application/json");
 }
  

Responsecontent:System.Net.Http.StringContent

第二枪:

    public List<Cell> Get()
    {
        Cell c = new Models.Cell("Cell1");
        List<Cell> list = new List<Cell>();
        list.Add(c);
        return list;
    }
  

Responsecontent:System.Collections.Generic.List`1 [TestApp.Models.Cell]

这是我访问端点的方式:

$.ajax({
            url: "http://localhost:54787/Cell/Get",
            type: "GET",
            contentType:"application/json",
            accepts: {
                text: "application/json"
            },       
            success: function (response) {
                $("#result").html(JSON.parse(response));
            },
            error: function (xhr, status) {
                alert("error");
            }
        });

enter image description here

1 个答案:

答案 0 :(得分:1)

如果没有充分的理由手动进行序列化,则应该通过返回object而不是StringContent来使用Web API默认机制。例如,您可以更改方法以直接返回List<Cell>

public List<Cell> Get()
{
     // return List<Cell> just like you write a typical method
}

这样,您就不会再获得text/html了。但是,您仍然可以在Chrome中获取XML。这是因为Chrome的默认HTTP Accept标头包含application/xml,默认情况下,它在Web API中受支持。如果您不需要支持XML结果,那么您可以在启动期间通过以下代码将其删除(可能在Global.asax中)

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

PS:如果你不知道你是否需要XML,那么你就不需要它了。