How do you set the content type for a WebMatrix/Razor Response?
Asked Answered
D

3

18

I'd like to return some XML instead of HTML in my WebMatrix cshtml file? How do you change the content type header?

Derosa answered 6/7, 2010 at 22:6 Comment(1)
I just had to figure this out so I'm posting for others to find the answer in the future.Derosa
D
24

Use the Response.ContentType property at the top of your .cshtml file then include the XML in the content of the view:

@{ 
   Response.ContentType = "application/xml";
}
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Dial>415-123-4567</Dial>
</Response>
Derosa answered 6/7, 2010 at 22:7 Comment(2)
Wow!! You edited your answer to match mine rather than select mine as the accepted answer?? That's cold, man... ice cold. (Check the revisions everybody)Yeeyegg
It's a wiki, you should have proposed an edit or commented on this one. Mine got out of date, so I updated it.Derosa
Y
19

At the top of your Razor file, set the ContentType of the Response object:

@{
  Response.ContentType = "application/xml";
}
... xml here ...
Yeeyegg answered 20/1, 2011 at 4:5 Comment(2)
At the time I wrote the other answer (first beta) that property wasn't accessible. I'll try that out now, thanks!Derosa
@John if the above worked for you would you consider changing the accepted answer? The above is possibly more correct, though both achieve the desired result.Integument
F
0

If you are using ASP.NET MVC, you can choose to make the change in your action method in the controller, like so:

public ActionResult MyAction() {
    Response.ContentType = "text/xml";
    return View();
}
Firecrest answered 16/1, 2012 at 22:56 Comment(2)
This doesn't apply to just plain .cshtml files outside of ASP.NET MVCDerosa
Thanks @JohnSheehan, I updated my answer to include that note.Firecrest

© 2022 - 2024 — McMap. All rights reserved.