Getting web application URI at startup

I need to find out the base URI of an ASP.NET web API application hosted in IIS 7.5+ right after the application starts, but before any client request possibly reaches it. The scenario I need is as follows: periodic checking is performed by a timer that runs independently of user requests and which runs with the application (the same process); if this check passes certain conditions, some registered users will receive an email with a hyperlink to my web application. Now I don’t want to hardcode this link anywhere, but rather get it dynamically from the web application itself. It would be easy to understand this from the context of the client request and then cache it in memory, but as you can imagine, the timer may disappear before any request reaches the server.

How could I correctly determine the application base URI? I thought that the Global.asax.cs file would be the most suitable place during the launch of the web application, but I could not find anything useful.

+4
source share
1 answer

Given the full URL, for example http://mydomain.com/MyApplication/Controller/Action , you can get some of this information from the System.Web.Hosting.HostingEnvironment.ApplicationHost object. You can get the following:

  • ApplicationVirtualPath β†’ "/ MyApplication"
  • SiteName => "Default Website"

However, you will not be able to get the domain name before the real request appears. This is because the IIS website can accept requests for different domains, some of which are known only through DNS and are never configured anywhere.

For example, your site may respond to both mydomain.com and www.mydomain.com . Which one is the correct one that you want to add to your link?

You can configure your IIS website only to accept connections that request a specific host, but that cannot be received from an ASP.NET application.

+3
source

Source: https://habr.com/ru/post/1485050/


All Articles