Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC, not "supposed" to use HttpContext.Current anymore?

Someone in a post here, commented that you should not use HttpContext.Current when using MVC, rather, you should be using ControllerBase.ControllerContext. In some respects, this makes sense, but in other respects it doesn't.

For example, ControllerContext is an instance variable, so everywhere I want to reference, say, my Session variables, I need to have a reference to the Controller? Why are we "not supposed" to be using HttpContext.Current in MVC, when you still can? Is there an "appropriate" MVC "way" to get at my Session object without having to have a reference to the Controller?

I know test-wise, it is better for reasons stated in many other places, but I am working on a project that manages Session variables and references HttpContext.Current and I want to know if there is a better way to get my hands on the Session object without passing a reference to the controller.

like image 210
gangelo Avatar asked Feb 02 '12 20:02

gangelo


2 Answers

This is mainly since unit testing would be very difficult if you use HttpContext.Current since mocking this value is not possible using normal mock frameworks.

HttpContext.Current also makes for more brittle code since it can be abused and misused. For example, you can use it in business layer since it is convenient but it will break if you choose to use an alternative presentation layer other than ASP.NET.

Generally static methods are nowadays frowned upon since they cannot be dependency-injected.

like image 134
Aliostad Avatar answered Oct 31 '22 23:10

Aliostad


Your one post was due to Mock testing, where depending on the Mock there may not be a HttpContext, only a controller context. Otherwise, I do use HttpContext.Current, just not in my unit tests.

like image 27
Erik Philips Avatar answered Oct 31 '22 21:10

Erik Philips