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

查看:25
本文介绍了如何从 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 始终为 null.

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 返回 NULL即通过范围服务注入它也不起作用.

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?

推荐答案

HttpContext 在 http 请求点击您的网站时被填充(非常简单的解释).

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天全站免登陆