Inject HttpContext in ASP.Net 5 -
i want inject httpcontext controller's constructor. knows how configure in configureservices()?
thanks
injecting httpcontext
directly in dependencies not recommended approach. instead, should use ihttpcontextaccessor
:
public class mycomponent : imycomponent { private readonly ihttpcontextaccessor contextaccessor; public mycomponent(ihttpcontextaccessor contextaccessor) { this.contextaccessor = contextaccessor; } public string getdatafromsession() { return contextaccessor.httpcontext.session.getstring(*key*); } }
that said, it's not needed in controller, can retrieve current httpcontext
using context
property.
of course, due way controllers created, property unavailable when instantiate controller, don't try access constructor. in case, try refactor code avoid accessing httpcontext
there or use ihttpcontextaccessor
replacement.
Comments
Post a Comment