40

I want to return a View() from an action, and the resulting response should have a content type of text/xml instead of the default text/html.

I have tried the following, with no success:

Response.ContentType = "text/xml"; 
return View();

I know that you can specify the content type by returning ContentResult, but that doesn't render my View.

I'm hoping I don't need to render the view to a string then use return Content(), so I'm probably overlooking some easy way.

andreialecu
  • 3,639
  • 3
  • 28
  • 36
  • 1
    I'm surprised no one spotted this as a duplicate: http://stackoverflow.com/questions/134905/what-is-the-best-way-to-return-xml-from-a-controllers-action-in-asp-net-mvc – Tomas Aschan Jun 22 '09 at 12:52
  • @TomasLycken, it may be because legenden and myself are putting the XML itself in the View and just desiring to set the ContentType of the View, not build XML in the Controller then pass it to the View. These are definitely two different methods. – John Washam Sep 11 '13 at 20:34
  • 1
    Another note to everyone is that this content type string can be referenced as `System.Net.Mime.MediaTypeNames.Text.Xml`. – jamiebarrow Nov 04 '13 at 15:07

6 Answers6

56
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" 
    ContentType="text/xml" %>
skeletank
  • 2,880
  • 5
  • 43
  • 75
eu-ge-ne
  • 28,023
  • 6
  • 71
  • 62
  • beautiful, I wasn't aware that you could set the ContentType on the page itself. This is awesomeness :P – Anthony Shaw Sep 28 '11 at 19:29
  • 2
    and if you have razor view, then it should be `@{ Response.ContentType = System.Net.Mime.MediaTypeNames.Text.Xml; }` – avs099 Apr 04 '15 at 14:04
43

You need to render the string. To return text/xml do the following:

return new ContentResult {
    ContentType = "text/xml",
    Content = UTF8.GetString(yourXmlString),
    ContentEncoding = System.Text.Encoding.UTF8
}; 
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Alex
  • 75,813
  • 86
  • 255
  • 348
7

Users control (ASCX) doesn't accept ContentType="text/xml".

Solution:

public ActionResult xxx()
  {
     Response.ContentType = "text/xml";
     return View("xxx.ascx");
  }
jmav
  • 3,119
  • 4
  • 27
  • 27
1

If you're looking for Razor (.cshtml) view then set content type in the view code:

@{
    Response.ContentType = "text/xml";
}
Alex from Jitbit
  • 53,710
  • 19
  • 160
  • 149
1

You need a view that doesn't override things and generate HTML, including its own context-type.

A custom view can directly render to Response.Write (see JsonResult in Reflector for a class that is very similar to what you would need).

To render XML without a intermediate string, save your XML to an XmlWriter created over Response.Output.

Richard
  • 106,783
  • 21
  • 203
  • 265
0

Have you tried setting the response.content from the view's pre render method in the codebehind page? that's obviously assuming you're using the webform view engine

Joel Martinez
  • 46,929
  • 26
  • 130
  • 185