繁体   English   中英

如何在Global.aspx的Application_Start中获取完整的主机名+端口号?

[英]How to get full host name + port number in Application_Start of Global.aspx?

我试过了

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

谁知道如何实现这一目标?

Web应用程序启动时,不会处理HTTP请求。

您可能希望处理定义Application_BeginRequest(Object Sender,EventArgs e)方法,其中Request上下文可用。

编辑:这是一个代码示例,其灵感来自Mike Volodarsky的博客,Michael Shimmins链接到:

    void Application_BeginRequest(Object source, EventArgs e)
    {
        HttpApplication app = (HttpApplication)source;
        var host = FirstRequestInitialisation.Initialise(app.Context);
    }

    static class FirstRequestInitialisation
    {
        private static string host = null;
        private static Object s_lock = new Object();

        // Initialise only on the first request
        public static string Initialise(HttpContext context)
        {
            if (string.IsNullOrEmpty(host))
            {
                lock (s_lock)
                {
                    if (string.IsNullOrEmpty(host))
                    {
                        var uri = context.Request.Url;
                        host = uri.GetLeftPart(UriPartial.Authority);
                    }
                }
            }

            return host;
        }
    }

接受的答案是好的,但在大多数情况下(如果第一个请求是HTTP请求),您应该更好地使用Session_Start事件,每个用户每20分钟左右调用一次(不确定会话有效多长时间)。 每个请求都会触发Application_BeginRequest

public void Session_Start(Object source, EventArgs e)
{
   //Request / Request.Url is available here :)
}

如果有人决定真正搜索这个主题,那就回答这个问题......

这适用于任何模式的应用程序启动...

typeof(HttpContext).GetField("_request", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(HttpContext.Current)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM