Web API return XML

天大地大妈咪最大 提交于 2020-01-04 15:14:39

问题


I'm trying to display the returned data as xml, but it returns in plain text. I've this code:

context.Response.AddHeader("Content-Type", "text/xml");
context.Response.Write("<pre>" + HttpUtility.HtmlEncode(writer) + "</pre>");

I'am using this :

using (XmlTextWriter writer = new XmlTextWriter(context.Response.OutputStream, System.Text.Encoding.UTF8))
                            {

... write the xml

}

... and create the XML.

This is how I send: context.Response.Write("<pre>" + HttpUtility.HtmlEncode(writer) + "</pre>");

How can i return XML in RAW with tags and all?


回答1:


HttpConfiguration.Formatters contains various formatters to serialize your model. Instead of writing directly to Response, consider your action to return a model or XDocument, and then make sure that you have XmlFormatter set in HttpConfiguration.Formatters to actually serialize it as XML.




回答2:


Honestly the right answer in Web API is to either do content negotiation as @LB2 is suggesting.

If we look at the way you are doing this there are a few things that are incorrect.

  1. You are trying to use HttpContext.Current to write directly to the output, although this works it's not a recommended practice because your pretty much bypass the whole pipeline, and lose many potential benefits of Web API.
  2. The following line:

context.Response.Write("<pre>" + HttpUtility.HtmlEncode(writer) + "</pre>");

Doesn't write any XML out, and basically makes the XML invalid. If you removed it things will start to seemingly work.

  1. The real alternative is either to follow LB2's suggestion, though it's not very easy to suppress content negotiation for one action. Another (the official recommended) approach is to do the following.

    public HttpResponseMessage GetOrder()
    {
        // Sample object data
        Order order = new Order();
        order.Id = "A100";
        order.OrderedDate = DateTime.Now;
        order.OrderTotal = 150.00;
    
        // Explicitly override content negotiation and return XML
        return Request.CreateResponse<Order>(HttpStatusCode.OK, order, Configuration.Formatters.XmlFormatter);
    }
    

See this link for more info: http://blogs.msdn.com/b/kiranchalla/archive/2012/02/25/content-negotiation-in-asp-net-mvc4-web-api-beta-part-1.aspx (Note: This is an old blog post and needs to be updated to latest version)



来源:https://stackoverflow.com/questions/23567789/web-api-return-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!