How to get HttpContext instance in normal class


#1

I didn’t found HttpContext.Current in core framework, looks its already been removed out.
now i have several normal class (not middleware,controller) and i want to use HttpContext within the code, how can i to get the HttpContext back for working.

Thanks!


#2

You may use the HttpContextAccessor. However, IMO, you should avoid this.
What you want is actually a hidden dependency that comes with a runtime cost (the HttpContext has to be flowed through the execution contexts) but, most importantly, your code depends on the HttpContext in an invisible manner. The more I grew up, the more I think hidden dependencies should be avoided: if a piece of long-lived code depends on transient or scoped objects, just give it them by parameters…


.NET Foundation Website | Blog | Projects | Code of Conduct