I'd like to return some XML instead of HTML in my WebMatrix cshtml file? How do you change the content type header?
How do you set the content type for a WebMatrix/Razor Response?
Asked Answered
I just had to figure this out so I'm posting for others to find the answer in the future. –
Derosa
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>
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
At the top of your Razor file, set the ContentType of the Response object:
@{
Response.ContentType = "application/xml";
}
... xml here ...
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
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();
}
This doesn't apply to just plain .cshtml files outside of ASP.NET MVC –
Derosa
Thanks @JohnSheehan, I updated my answer to include that note. –
Firecrest
© 2022 - 2024 — McMap. All rights reserved.