【问题标题】:How to response with text/xml media type in ASP.NET Web Api如何在 ASP.NET Web Api 中使用 text/xml 媒体类型进行响应
【发布时间】:2015-04-01 04:48:15
【问题描述】:

这是我的 api 操作:

[HttpGet]
public IHttpActionResult Get()
{
    HttpContext.Current.Response.ContentType = "text/xml";
    string foo = GetXmlString();
    return Ok(foo);
}

我希望当相关请求发生时响应可以返回“text/xml”类型。如果我什么都不做(使用默认配置),如果我做了以下配置,则返回类型将是“application/xml”:

var applicationXml = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(_ => _.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(applicationXml);
var textXml = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(_ => _.MediaType == "text/xml");
if (textXml == null)
{
    config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
}

它将改用“application/json”。但我不想删除默认媒体类型“application/json”。

为什么不能按预期应用操作级别配置,而是使用全局配置?我对这种行为感到很困惑。

【问题讨论】:

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


    【解决方案1】:

    你可以使用配置文件来做到这一点

    将此添加到WebApiConfig

    config.Formatters.Clear();
    config.Formatters.Add(new XmlMediaTypeFormatter());
    // config.Formatters.Add(new JsonMediaTypeFormatter());
    // config.Formatters.Add(new FormUrlEncodedMediaTypeFormatter());
    

    【讨论】:

      【解决方案2】:

      如果您希望此特定请求以特定的“Content-Type”返回,您可以使用Request.CreateResponse 并传入您想要的格式化程序:

      return Request.CreateResponse(HttpStatusCode.Accepted, new StringContent(""),
                                    new XmlMediaTypeFormatter());
      

      您可能还想查看 this post 关于 WebAPI 中的内容协商

      【讨论】:

        【解决方案3】:

        你可以试试这些:

        01

        return Request.CreateResponse(HttpStatusCode.Accepted, new StringContent(""),
                                      new XmlMediaTypeFormatter());
        

        02

        return Request.CreateResponse(HttpStatusCode.Accepted, new StringContent(""),
                                      new MediaTypeHeaderValue("text/xml"));
        

        03

        return Request.CreateResponse(HttpStatusCode.Accepted, new StringContent(""),
                                      Configuration.Formatters.XmlFormatter);
        

        【讨论】:

          猜你喜欢
          • 2023-03-03
          • 1970-01-01
          • 2013-12-02
          • 2017-08-19
          • 1970-01-01
          • 2017-12-27
          • 1970-01-01
          • 2021-03-31
          • 2017-08-08
          相关资源
          最近更新 更多