5

我需要找出托管在 IIS 7.5+ 中的 ASP.NET Web API 应用程序的基本 URI,在应用程序启动之后,但在任何客户端请求可能到达之前。我需要这个的场景如下:通过一个独立于用户请求运行并与应用程序启动(相同过程)一起触发的计时器执行定期检查;如果此检查通过某些条件,一些注册用户将收到一封电子邮件,其中包含指向我的 Web 应用程序的超链接。现在,我不想在任何地方对该链接进行硬编码,而是从 Web 应用程序本身动态获取它。从客户端请求的上下文中找出它很简单,然后将其缓存在内存中,但正如您可以想象的那样,计时器可能会在任何请求到达服务器之前关闭。

那么我如何才能正确确定应用程序的基本 URI?在网络应用程序启动期间,我认为最合适的位置是Global.asax.cs文件,但我找不到任何看起来有用的东西。

4

1 回答 1

6

Given a full URL such as "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 Web Site"

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

For example, your website could respond to both mydomain.com and www.mydomain.com. Which is the correct one that you want to put in your link?

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

于 2013-06-07T14:29:42.070 回答