为什么我的Web API只返回JSON?

时间:2014-05-14 21:09:13

标签: asp.net-web-api .net-4.5

我刚刚将Update 2 RTM应用到Visual Studio 2013并启动了一个新的Web API项目。我有一个基本服务返回一些人物。

我正在尝试使用内容协商来返回JSON或XML,具体取决于Accept标头。无论Accept标头如何,我都会获得JSON。如何对此进行故障排除并根据标头返回XML或JSON?

以下是Fiddler的标题:Accept: application/xml

这是我的Get()方法的主体:

var patient = this.patientRepository.GetPatients().Where(p => p.Identifier == id).FirstOrDefault();

IContentNegotiator negotiator = this.Configuration.Services.GetContentNegotiator();

ContentNegotiationResult result = negotiator.Negotiate(typeof(Patient), this.Request, this.Configuration.Formatters);

if (result == null)
{
    var response = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
    throw new HttpResponseException(response);
}

return new HttpResponseMessage()
{
    Content = new ObjectContent<Patient>(patient, result.Formatter, result.MediaType.MediaType)
};

谢谢!

更新 - 这是WebApiConfig.cs。我添加了添加XmlMediaTypeFormatter的行。默认情况下,它不包括在内。无论哪种方式,问题都没有得到解决。

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services
    GlobalConfiguration.Configuration.Formatters.Add(new XmlMediaTypeFormatter());


    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

0 个答案:

没有答案