Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC HttpContext.Response.Write() vs Content()

Tags:

asp.net-mvc

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?

like image 976
Orif Khodjaev Avatar asked Sep 14 '25 17:09

Orif Khodjaev


1 Answers

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.

like image 129
Darin Dimitrov Avatar answered Sep 16 '25 08:09

Darin Dimitrov