How do I get the website URL or access the HttpContext from a IHostedService in ASP.NET Core?

大兔子大兔子 提交于 2019-12-13 03:18:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!