Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What is the alternative to get the HttpContext.Current in .net core ? #689

Closed
synckarthik opened this issue Jun 14, 2017 · 10 comments
Closed

Comments

@synckarthik
Copy link

Any one can suggest how to use the HttpContext.Current in .net core ?

@h3smith
Copy link

h3smith commented Jun 14, 2017

In what context? There are several ways to get it - you can't grab it statically anymore.

@ukphillips
Copy link

The correct (and only) way to really do this is to inject the HttpContextAccessor into the class or service you want to use it in.

@Petermarcu
Copy link
Member

This issue is probably better to open on the aspnet/home repo where more people that know the details of HttpContext would be watching.

@Petermarcu
Copy link
Member

@Eilon do you know who could help here?

@ukphillips
Copy link

This should be able to get you in the right direction. https://www.strathweb.com/2016/12/accessing-httpcontext-outside-of-framework-components-in-asp-net-core/

@Eilon
Copy link
Member

Eilon commented Jun 22, 2017

That linked blog post has the answer. However, in general we don't recommend using that pattern at all. Any component that needs to know the current HttpContext needs to have the HttpContext passed to it - the same as you would do for any other piece of data that the component needs.

@richlander
Copy link
Member

Please continue the conversation on the aspnet/home repo if you need more information. Thanks.

@naveedahmed1
Copy link

@Eilon so for the sake of clarity, suppose we have a repository class, that neesd access to HttpContext.Current , we would first inject HttpContextAccessor in the controller calling that class, and then pass reference to context to the class from controller correct?

@Eilon
Copy link
Member

Eilon commented Sep 6, 2017

@naveedahmed1 yes that sounds like it would work. However, I think in common/popular app architectures a "repository" class generally doesn't need access to HttpContext.Current. There would usually be some other app/scenario-specific interface that you'd create that the "repository" would depend on, and the implementation of that interface would use something like IHttpContextAccessor to get the data it needs. But both ways should work.

@naveedahmed1
Copy link

Thank you so much @Eilon for quick reply, sorry I meant a utility class but got your point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants