问题描述
谁能告诉我是否有办法在 global.asax 中的 Application_Start 事件中获取我网站的域名?
Can anybody tell me if there is a way for me to get the domain name of my site in the Application_Start event in the global.asax?
通常我只是从 Context.Request.ServerVariables["SERVER_NAME"] 中获取它,但这不可用.理想情况下,我还想从启动应用程序的请求中获取 URL.
Normally I'd just get it from Context.Request.ServerVariables["SERVER_NAME"], but this is not available. I'd ideally also like to get the URL from the request that kicked off the application.
嗯 - 从下面的答案来看,似乎在 IIS7 上会有所不同.这是新的,现在有设计指南试图阻止你这样做:
Hmm - from answers below, it would seem that being on IIS7 makes a difference here. This is new and there are now design guidelines to try and stop you from doing it:
推荐答案
您可以访问 上下文 通过静态 HttpContext.Current 成员.
You can access the Context through the static HttpContext.Current member.
HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
HttpContext.Current.Request.Url;
编辑,根据您的一些评论,我做了一些额外的研究
Edit, Based on some of your comments I did some additional research
此错误是由于 IIS7 集成管道中的设计更改导致 Application_Start 事件中的请求上下文不可用.当使用经典模式(在以前版本的 IIS 上运行时的唯一模式)时,请求上下文过去是可用的,即使 Application_Start 事件一直旨在作为应用程序生命周期中的全局且与请求无关的事件.尽管如此,由于 ASP.NET 应用程序总是由应用程序的第一个请求启动,因此过去可以通过静态 HttpContext.Current 字段获取请求上下文.
所以你有两个选择
- 将您的应用程序代码更改为不使用请求上下文(推荐).
- 将应用程序移至经典模式(不推荐).
这篇关于全局 ASAX - 获取服务器名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!