如何获取完整的主机名 + Global.aspx 的 Application_Start 中的端口号?
我尝试过
Uri uri = HttpContext.Current.Request.Url;
String host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
,它在我的本地计算机上运行良好,但是当发布到 IIS7 时,出现异常,
System.Web.HttpException: Request is not available in this context
有人知道如何实现这一点吗?
I tried
Uri uri = HttpContext.Current.Request.Url;
String host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
and it worked well on my local machine, but when being published to IIS7, there is an exception saying
System.Web.HttpException: Request is not available in this context
Anyone know how to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您的 Web 应用程序启动时,不会处理任何 HTTP 请求。
您可能需要处理定义 Application_BeginRequest(Object Sender, EventArgs e) 方法,其中请求上下文可用。
编辑:以下是受 Michael Shimmins 链接到的 Mike Volodarsky 博客启发的代码示例:
When your web application starts, there is no HTTP request being handled.
You may want to handle define the Application_BeginRequest(Object Sender, EventArgs e) method in which the the Request context is available.
Edit: Here is a code sample inspired by the Mike Volodarsky's blog that Michael Shimmins linked to:
接受的答案很好,但在大多数情况下(如果第一个请求是 HTTP 请求),您最好使用
Session_Start
事件,每个用户每 20 分钟左右调用一次该事件(不知道如何会话有效期长)。Application_BeginRequest
将在每个请求时触发。The accepted answer is good, but in most cases (if the first request is a HTTP Request) you should better use the
Session_Start
event, which is called once per user every 20 minutes or so (not sure how long the session is valid).Application_BeginRequest
will be fired at every Request.只是回答这个问题,以便如果有人决定实际搜索该主题...
这适用于以任何模式启动的应用程序...
Just answering this so if someone ever decides to actually search on this topic...
This works on application start in any mode...