全局 ASAX - 获取服务器名称 [英] Global ASAX - get the server name

查看:13
本文介绍了全局 ASAX - 获取服务器名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我是否有办法在 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:

IIS 博客

推荐答案

您可以访问 上下文 通过静态 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 字段获取请求上下文.

This error is due to a design change in the IIS7 Integrated pipeline that makes the request context unavailable in Application_Start event. When using the Classic mode (the only mode when running on previous versions of IIS), the request context used to be available, even though the Application_Start event has always been intended as a global and request-agnostic event in the application lifetime. Despite this, because ASP.NET applications were always started by the first request to the app, it used to be possible to get to the request context through the static HttpContext.Current field.

所以你有两个选择

  1. 将您的应用程序代码更改为不使用请求上下文(推荐).
  2. 将应用程序移至经典模式(不推荐).

http://mvolo.com/iis7-integrated-mode-request-is-not-available-in-this-context-exception-in-applicationstart/

这篇关于全局 ASAX - 获取服务器名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆