如何从ASP.NET Core中的IHostedService获取网站URL或访问HttpContext?

编程入门 行业动态 更新时间:2024-10-24 22:20:32
本文介绍了如何从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?

本文发布于:2023-11-14 09:11:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586807.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:网站   Core   ASP   NET   HttpContext

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!