c# - How to get HttpContext.Current in ASP.NET Core? -
this question has answer here:
we rewriting/converting our asp.net webforms application using asp.net core. trying avoid re-engineering as possible.
there section use httpcontext
in class library check current state. how can access httpcontext.current
in .net core 1.0?
var current = httpcontext.current; if (current == null) { // here // string connection = configuration.getconnectionstring("mydb"); }
i need access in order construct current application host.
$"{current.request.url.scheme}://{current.request.url.host}{(current.request.url.port == 80 ? "" : ":" + current.request.url.port)}";
as general rule, converting web forms or mvc5 application asp.net core will require significant amount of refactoring.
getting httpcontext.current
isn't possible, because current
removed in asp.net core. accessing current http context separate class library type of messy architecture asp.net core tries avoid.
in asp.net core, can access current http context controller using httpcontext
. closest thing original code sample pass httpcontext
method calling:
public class homecontroller : controller { public iactionresult index() { mymethod(httpcontext); // other code } } public void mymethod(microsoft.aspnetcore.http.httpcontext context) { var host = $"{context.request.scheme}://{context.request.host}"; // other code }
it's possible context using ihttpcontextaccessor
asp.net core dependency injection system. if have controller or middleware function requests interface service container:
public mymiddleware(ihttpcontextaccessor httpcontextaccessor) { _httpcontextaccessor = httpcontextaccessor; }
you can access current http context in safe way:
var context = _httpcontextaccessor.httpcontext;
since ihttpcontextaccessor
isn't added service container default, you'll have register it:
public void configureservices(iservicecollection services) { services.tryaddsingleton<ihttpcontextaccessor, httpcontextaccessor>(); // other code... }
Comments
Post a Comment