Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

c# - How to get full host name + port number in Application_Start of Global.aspx?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

    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;
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...