.NET MVC 4内容协商不起作用

时间:2012-11-06 19:44:41

标签: asp.net-mvc-4 asp.net-web-api content-negotiation

我有一个使用.NET MVC 4在C#中实现的Web服务,但由于某种原因,他们总是以XML格式返回数据,尽管我发送的是Accept:application / json标头。什么想法可能是错的?

提前致谢

更新:控制器代码如下所示

public HttpResponseMessage GetData()
{
     ...
     DashboardInformation d = new DashboardInformation()
     {
            Name = "Test",
            employees = employees,
            shortcuts = shortcuts,
            notes = dashboardNoteList,
            timeEntries = dashboardTimeList,
            timeTracker = timeTracker,
            timeTrackerFromDate = ToUnixTimestamp(fromDate),
            timeTrackerToDate = ToUnixTimestamp(toDate),
            timeSummary = timeSummary,
            userInfo = uInfo
     };
     return Request.CreateResponse(HttpStatusCode.OK, d);
}

更新2 :原始请求和响应

请求

GET /RestService/api/Dashboard/GetData HTTP/1.1
Host: xxx
Connection: keep-alive
Cache-Control: max-age=0
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko)         Chrome/22.0.1229.94 Safari/537.4
Accept: application/json, text/javascript, */*; q=0.01
Referer: http://xxx/Firm4.0/dashboard.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: es-ES,es;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

响应

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/xml; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 06 Nov 2012 19:01:59 GMT
Content-Length: 3610
...

2 个答案:

答案 0 :(得分:0)

我需要更多信息来诊断您的问题

  1. 是否以任何方式修改了一组默认格式化程序?例如,在App_Start \ WebApi.Config.cs中:

        config.Formatters.Clear();
        config.Formatters.Add(...);
    
  2. 您尝试呼叫的ApiController中的操作如何?

  3. 您能否向我们提供原始请求和回复消息?

答案 1 :(得分:0)

我发现了问题。有一个自定义IContentNegotiator实现,它总是返回一个XmlMediaTypeFormatter。谢谢大家的帮助。