如何从ASP.NET Core中的IHostedService获取网站URL或访问HttpContext? [英] How do I get the website URL or access the HttpContext from a IHostedService in ASP.NET Core?

查看:153
本文介绍了如何从ASP.NET Core中的IHostedService获取网站URL或访问HttpContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的MultiTenant ASP.NET Core 2.2应用程序中,我们从URI确定租户。

In our MultiTenant ASP.NET Core 2.2 app, we determine the tenant from the URI.

如何从IHostedService获取网站URL?
HttpContext始终为空。

How can get the website URL from an IHostedService? The HttpContext is always null.

IHttpContextAccessor.HttpContext始终为空

The IHttpContextAccessor.HttpContext IS ALWAYS NULL

public MyHostedService(ILogger<TurnTimeTask> logger, 
    IHttpContextAccessor httpContextAccessor)
{
    _logger = logger;
    _httpContextAccessor = httpContextAccessor;
}

即使在Scope中运行IHostedService也会为httpContextAccessor.HttpContext $ b返回NULL。 $ b即通过作用域服务注入它也不起作用。

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
}

还有其他方法可以从IHostedService获取网站的URL?

Is there any other way to get the website's URL from an IHostedService?

推荐答案

http请求到达您的网站时,就会填充HttpContext (非常简单的解释)。

HttpContext is populated when a http request hits your site (very simple explanation).

将IHostedService看作是在后台运行的独立于任何http请求的东西,它在与例如请求完全不同的上下文中运行

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与ASP.NET Core紧密相关,而IHostedService不需要ASP.NET Core即可运行。

HttpContext is heavily tied to ASP.NET Core while IHostedService does not need ASP.NET Core to run.

这篇关于如何从ASP.NET Core中的IHostedService获取网站URL或访问HttpContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆