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.
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.
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.
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