0

I have a web app using .net core 3.1 on IIS 10. I have my main domain set up and I have 3 alias domains that resolve to the main domain name. For my app I want to know which domain the user used to access the site.

How could I determine that? Any help to get me pointed in the right direction would be great.

Thanks!

Jason
  • 93
  • 1
  • 8

1 Answers1

1

If I understand this correctly, an alias domain is just an additional domain which points to the same server as your main domain, so you are not being redirected to the main domain? I.e the address bar still shows the URL the user used to access your site. In that case, it should be as easy as reading the host name from the current URL. You can grab that info via the IHttpContextAccessor.

Step 1, register it as a service in the startup.cs file

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Step 2, make your controller depend on it, via DI:

private readonly IHttpContextAccessor _httpContextAccessor;
public YourController(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}

Step 3, read the info from the httpContextAccessor:

string domain = _httpContextAccessor.HttpContext.Request.Host.Value;
HaukurHaf
  • 13,522
  • 5
  • 44
  • 59
  • 1
    Injecting a `IHttpContextAccessor` into controller (which in most cases derive from Microsoft's controller) does not make much sense since `HttpContext` is already accessible without need of special accessor via property with the same name. You wrote this most probably for the sake of example, but maybe consider changing the `YourController` to some sort of manager, helper or any service in general, having in mind that OP didn't state where he indend to use such logic. – Prolog Aug 30 '20 at 21:46
  • Thanks for your quick reply, and for taking the time to post the code. Right now the address bar shows the main domain, no matter which domain was initially entered so yes it's redirecting. I'm not sure how to intercept the request and grab the alias. Maybe I can reconfigure so it delivers them to the same destination using the alias. – Jason Aug 30 '20 at 21:47
  • If it's indeed redirecting, then your only hope is that the initial URL is exposed via an HTTP header which is passed along with the redirect, such as the REFERER or X_FORWARDED_FOR headers. – HaukurHaf Aug 30 '20 at 21:50
  • @Prolog - thanks for your reply. The app has a free version and a paid version. Paid users can use both the main domain name and the alias name. Free users can only use the main domain name. Once I know which one they come in on, I can write the logic to grant/deny them access to the site using the domain used. – Jason Aug 30 '20 at 21:51
  • I was able to adjust the IIS configuration, specifically the rewrite module so the redirect didn't occur. Then it was easy to access the alias name using the httpContext as described above. Thanks for your help guys. – Jason Aug 31 '20 at 02:30