Asp.net web api 为什么asp.net webAPI总是返回文本/html?

Asp.net web api 为什么asp.net webAPI总是返回文本/html?,asp.net-web-api,Asp.net Web Api,我想创建返回json的Web服务。但是,我总是将“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

我想创建返回json的Web服务。但是,我总是将“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.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");
            }
        });

如果没有充分的理由手动执行序列化,则应使用Web API默认机制,返回对象而不是StringContent。例如,您可以将方法更改为直接返回
List

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

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

您如何测试端点?我正在从chrome调用
/Cell/Get
。我还尝试了一个jQuery$.ajaxget请求,并检查了chrome的网络监视器。你看到了吗@user66875,框架的内容协商者返回请求所要求的媒体类型,前提是它能够支持该类型。如果您是从浏览器调用它,则默认情况下浏览器将要求
text/html
谢谢。我已经更新了我的帖子并添加了你代码的结果。我真的不明白为什么它仍然返回
text/html
public List<Cell> Get()
{
     // return List<Cell> just like you write a typical method
}
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();