MVC, and not "supposedly" to use HttpContext.Current more?

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

For example, ControllerContext is an instance variable, so wherever I want to reference, say, my session variables, do I need to have a reference to the controller? Why do we not โ€œassumeโ€ to use HttpContext.Current in MVC when you can still? Is there a โ€œsuitableโ€ MVC โ€œpathโ€ to access my Session object without having to have a reference to the controller?

I know the test-wise, this is better for the reasons outlined in many other places, but I'm working on a project that manages session variables and HttpContext.Current links and I want to know if there is a better way to get my hands on a Session object, not passing the link to the controller.

+8
asp.net-mvc controller
source share
2 answers

This is mainly because unit testing would be very difficult if you are using HttpContext.Current , since mocking this value is not possible using regular frameworks.

HttpContext.Current also makes more fragile code, as it can be abused and abused. For example, you can use it in a business layer, as itโ€™s convenient, but it will break if you decide to use an alternative presentation layer other than ASP.NET.

In general, static methods are not currently approved because they cannot be injection dependent .

+7
source

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

+1
source

All Articles