在Application_Start上访问当前域名
通常,要访问当前域名,例如站点托管位置,我会执行类似的操作
string rURL = HttpContext.Current.Request.Url.ToString().ToLower();
,但 HttpContext
仅在 Application_BeginRequest
上无法在 Application_Start
上使用。
有什么想法吗?
Normally to access the current domain name e.g where the site is hosted I do something like
string rURL = HttpContext.Current.Request.Url.ToString().ToLower();
But HttpContext
is not avaible on Application_Start
only from Application_BeginRequest
.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
实现此目的的一种方法是有点作弊并附带警告,那就是使用
System.Web.Hosting.HostingEnvironment.SiteName
。因此,这看起来像:
现在对于这些注意事项:
就我的目的而言,在服务器上设置日志记录,其中 IIS 中有多个站点指向同一个物理文件夹,上述解决方案可能是最简单的解决方案。我并不是说这一定是“正确”的答案,但它应该被视为替代方案。
One way of achieving this is a little bit of a cheat and comes with caveats, and that's to use
System.Web.Hosting.HostingEnvironment.SiteName
.So this would look like:
And now for those caveats:
For my purposes - setting up logging on servers where I had multiple sites in IIS pointing to the same physical folder - the above solution was probably the simplest and easiest. I'm not saying it's necessarily the 'right' answer, but it should be considered as an alternative.
单个 IIS 应用程序可以绑定到许多不同的 URL。
Application_Start
在收到任何请求之前触发,因此查找站点绑定的域名的唯一方法是查询 IIS。即使如此,您也可能无法得到答案 - 考虑应用程序绑定到通配符/默认主机名的情况。
更好的方法可能是查看
Application_AuthenticateRequest
。它在Application_BeginRequest
之前触发,并为您提供完整的HttpContext.Current.Request
对象。A single IIS application can be bound to many different URLs.
Application_Start
fires before any request has been received, so the only way to find the domain name to which the site is bound is to query IIS.Even then you may not be able to get an answer - consider the situation where an application is bound to a wildcard / default hostname.
A better approach may be to look at
Application_AuthenticateRequest
. This fires beforeApplication_BeginRequest
and does give you a fullHttpContext.Current.Request
object.尝试
Dns .GetHostName()
。您可以在 Gloabl.asax.cs 中使用它,无论是否在 Application_Start() 中。
在 Asp.net 4.5 MVC 中测试。
Try
Dns.GetHostName()
.You can use this in Gloabl.asax.cs, no matter within Application_Start() or not.
tested in Asp.net 4.5 MVC.
IIS 应用程序不知道在应用程序启动时从哪个域访问(请参阅绑定)。
The IIS application does not know what domain its accessed from (see bindings) at application start.