2012-01-14 59 views
1

有没有什么方法可以从Global.asax的Application_Start事件中确定托管网站的URL?如何确定Global.asax Application_Start事件中的服务器URL和端口

我试图存储的网址,以便我的应用程序可以生成从后台进程通过电子邮件发送的动态链接。

如果我尝试直接访问这个方法HttpApplication.Request对象,我得到一个运行时错误:

System.Web.HttpException: Request is not available in this context

+1

为什么不能在'Session_Start'中完成? – Oded 2012-01-14 22:06:33

+0

在集成模式下在IIS 7或更高版本上运行时,当前的HTTP上下文在Application_Start时不可用。正如@Oded所说,Session_Start会起作用 - 就像Application_BeginRequest一样,尽管Session_Start被调用的次数少得多。 – Dubs 2012-04-10 18:37:02

回答

0

我最终把我的代码放在Global.asax的Application_BeginRequest事件中。

 string url = this.Context.Request.Url.AbsoluteUri.Replace(this.Context.Request.Url.PathAndQuery, string.Empty) + this.Context.Request.ApplicationPath; 
     if (url[url.Length-1] != '/') 
     { 
      url = url + '/'; 
     } 
0

您可以从与下面的请求得到的网址:

this.Context.Request.Url

由此您可以确定地址,包括应用程序的端口号。

+0

这在我的本地开发机器(卡西尼)上工作,但我部署到我的服务器时出现错误。你知道是否有一些IIS设置可能需要设置使它以同样的方式工作? – YeahStu 2012-01-17 18:02:53

+0

你得到的错误是什么? – alhalama 2012-01-17 19:19:05

+0

System.Web.HttpException:请求在此上下文中不可用 – YeahStu 2012-01-17 21:22:49