Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top