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

1

0

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?

Tacnaarica answered 12/7, 2019 at 9:49 Comment(3)
Did you add IHttpContextAccessor to DI by a method AddHttpContextAccesor()?Samba
@BeniaminMakal yes. services.AddHttpContextAccessor(); doesn't work either.Tacnaarica
How did you call ProcessInScope? Before calling ProcessInScope, have you sent any reqeust to the server? _httpContextAccessor?.HttpContext?.Request will have value only when there is any request from client. Share us a demo and detail steps to reproduce your issue.Rainout
W
2

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.

Wulfe answered 12/7, 2019 at 15:37 Comment(3)
So you are saying the IHostedService is blind to the webserver's URL?Tacnaarica
If you have a service running on for example www.example.org, I would just add that to my appsettings and read it from there, does that work for you? You can't use HttpContext for this since it's tied to requests (which you don't have in a IHostedService) and it's also quite dangerous to trust HttpContext for getting the correct URL since it can be wrong behind a proxy/load balancer for example.Wulfe
thanks. The problem is that it would be too tedious in a multitenant environment. Will have to rethink this. Thanks!Tacnaarica

© 2022 - 2024 — McMap. All rights reserved.