问题
In our MultiTenant ASP.NET Core 2.2 app, we determine the tenant from the URI.
How can get the website URL from an IHostedService? The HttpContext is always null.
The IHttpContextAccessor.HttpContext IS ALWAYS NULL
public MyHostedService(ILogger<TurnTimeTask> logger,
IHttpContextAccessor httpContextAccessor)
{
_logger = logger;
_httpContextAccessor = httpContextAccessor;
}
Even running the IHostedService in Scope also returns NULL for the httpContextAccessor.HttpContext i.e. Injecting it through a Scoped Service doesn't work either.
public override Task ProcessInScope(IServiceProvider serviceProvider)
{
var request = _httpContextAccessor?.HttpContext?.Request;
//request is always null
}
Is there any other way to get the website's URL from an IHostedService?
回答1:
HttpContext is populated when a http request hits your site (very simple explanation).
Think of a IHostedService as something that runs in the background independent of any http requests, it runs in a completely different context than for example the requests that hits your controllers.
HttpContext is heavily tied to ASP.NET Core while IHostedService does not need ASP.NET Core to run.
来源:https://stackoverflow.com/questions/57004484/how-do-i-get-the-website-url-or-access-the-httpcontext-from-a-ihostedservice-in