【问题标题】:ASP.NET WebApi returns XML or json based on the request headerASP.NET WebApi 根据请求头返回 XML 或 json
【发布时间】:2018-07-20 12:52:00
【问题描述】:

在我的ASP.NET 项目中,所有WebApi 都回复json。为此在WebApiConfig.cs我设置了

config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());

现在,我只需更改一个 webapi 以根据标头中的请求返回 XML。

最好的做法是什么?有例子吗?

【问题讨论】:

  • 您应该阅读有关 Web API 中的内容协商

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


【解决方案1】:

将此添加到您的配置中:

config.Formatters.XmlFormatter.UseXmlSerializer = true;

那么你同时有 xml 和 json 序列化, 当您将请求的接受标头设置为“application/xml, xml/text”时,您将获得 xml,如果您将标头设置为“application/json, json/text”,则您将获得 json 结果 它被称为content negotiation

另一种做法是在具体方法中将对象序列化为xml

【讨论】:

    【解决方案2】:

    根据您的评论,我更新了WebApiConfig.cs

    public static void Register(HttpConfiguration config)
    {
        config.Formatters.Clear();
        config.Formatters.Add(new JsonMediaTypeFormatter());
        config.Formatters.Add(new XmlMediaTypeFormatter());
        config.Formatters.XmlFormatter.UseXmlSerializer = true;
    }
    

    然后在我想回复XML的webapi中

    public HttpResponseMessage GetCollections(int Id)
    {
        List<CollectionDTO> result = _collectionsLogic.GetCollections(Id);
    
        IContentNegotiator negotiator = this.Configuration.Services.GetContentNegotiator();
    
        ContentNegotiationResult resultFormatted = negotiator.Negotiate(
                typeof(List<CollectionDTO>), this.Request, this.Configuration.Formatters);
    
        if (result == null)
        {
            var response = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
            throw new HttpResponseException(response);
        }
    
        return new HttpResponseMessage()
        {
            Content = new ObjectContent<List<CollectionDTO>>(
                          result,
                          resultFormatted.Formatter,
                          resultFormatted.MediaType.MediaType
            )};
        }
    }
    

    例如,如果我用Postman 调用这个webapi,并在标题中插入Accept 等于application/xml,我将收到XML 格式的结果,否则为json

    【讨论】:

      猜你喜欢
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2012-08-02
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      相关资源
      最近更新 更多