How do I get the host domain name in ASP .NET without using HttpContext.Current.Request?

17,913

Solution 1

The reason that the domain is in the request is...that's what's being asked for. For example these are a few stackexchange sites from http://www.stackexchangesites.com/:

If you ping them, you'll see they all point to the same IP/Web Server and be served by the same app (or multiple apps in this case, but the example holds if it was one big one)...but the application doesn't know which one until a host header comes in with the request asking the server for that site. Each request may be to a different domain...so the application doesn't know it.

If however it doesn't change, you could store it as an appSetting in the web.config.

Solution 2

Use global.asax or write a HttpModule and subscribe to start request events. You will have the request passed into your event handler.

Share:
17,913
Badjer
Author by

Badjer

Updated on June 05, 2022

Comments

  • Badjer
    Badjer almost 2 years

    I've got an ASP .Net application running on IIS7. I'm using the current url that the site is running under to set some static properties on a class in my application. To do this, I'm getting the domain name using this (insde the class's static constructor):

    var host = HttpContext.Current.Request.Url.Host;
    

    And it works fine on my dev machine (windows XP / Cassini). However, when I deploy to IIS7, I get an exception: "Request is not available in this context".

    I'm guessing this is because I'm using this code in the static constructor of an object, which is getting executed in IIS before any requests come in; and Cassini doesn't trigger the static constructor until a request happens. Now, I didn't originally like the idea of pulling the domain name from the Request for this very reason, but it was the only place I found it =)

    So, does anyone know of another place that I can get the host domain name? I'm assuming that ASP .Net has got to be aware of it at some level independent of HttpRequests, I just don't know how to access it.

  • Badjer
    Badjer about 14 years
    Ah, right, then what I really should be doing is not initializing this stuff in a static constructor. In fact, if I want to be safe, I shouldn't even have my values be static at all - I should look them up again on every request, in case I'm getting requests from multiple domains (in my case I won't, but it's good to be aware of this). Thanks for the help - unfortunately, now I should refactor a bigger chunk of this legacy app than I'd like =)
  • Rafael Herscovici
    Rafael Herscovici over 8 years
    This only gets you the path, not the domain.