I've seen these two ways to send an xml response.
Option 1:
var response = System.Web.HttpContext.Current.Response;
response.Clear();
response.Write(sw.ToString());
response.ContentType = "text/xml";
response.End();
Option 2:
return Content(sw.ToString(), "text/xml");
Option 2 is way more convenient but are there any advantages in one over the other? Which one is preferred?
The great advantage of option 2 is that you will be able to unit test this controller action in isolation because it doesn't depend on the terrible HttpContext.Current
static property. Also it's a much more MVCish way to implement such functionality. In ASP.NET MVC, the C
stands for Controller and controllers have Actions that return ActionResult
. So ContentResult
is just one concrete implementation of an ActionResult that you could return from a Controller Action.
By the way did you know that every time an ASP.NET developer uses HttpContext.Current
in his application a kitten dies? So you can completely forget about Option 1. This doesn't exist. I wouldn't even call this an option. That's a crime against humanity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With