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

Leo*_*Leo 49 c# asp.net url hostname request

我试过了

Uri uri = HttpContext.Current.Request.Url;
String host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
Run Code Online (Sandbox Code Playgroud)

它在我的本地机器上运行良好,但在发布到IIS7时,有一个例外

System.Web.HttpException: Request is not available in this context
Run Code Online (Sandbox Code Playgroud)

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

csp*_*ton 60

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 不应该是`Uri uri = context.Request.Url;`也不能将下一行简化为仅仅`uri.GetLeftPart(UriPartial.Authority);` (3认同)
  • 为什么要投票呢?这是一个正确的建议. (2认同)

Vla*_*adL 9

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

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