How to Get Full Host Name + Port Number in Application_Start of Global.Aspx

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

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

Access current domain name on Application_Start

Try Dns.GetHostName().

You can use this in Gloabl.asax.cs, no matter within Application_Start() or not.

var hostName = Dns.GetHostName();

tested in Asp.net 4.5 MVC.

.NET - Get protocol, host, and port

The following (C#) code should do the trick

Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;

How to determine the server url and port in the Global.asax Application_Start event

I ended up putting my code in the Global.asax's Application_BeginRequest event.

        string url = this.Context.Request.Url.AbsoluteUri.Replace(this.Context.Request.Url.PathAndQuery, string.Empty) + this.Context.Request.ApplicationPath;
if (url[url.Length-1] != '/')
{
url = url + '/';
}

Not sure how I can determine my ASP.NET website domain and port, programatically

I don't think there is a sure way to do this:

  • IIS can map a number of ips, hostnames and ports to a web application
  • Each request can be bound to a different one

You probably need to do one of these things:

  • change your code so the binding is only needed when you have a request and not at application start
  • if you know the correct value before hand , you can set it by storing it via a configuration key

Request object in Application_Start event

Have a look at this:
http://mvolo.com/blogs/serverside/archive/2007/11/10/Integrated-mode-Request-is-not-available-in-this-context-in-Application_5F00_Start.aspx

In summary, the error occurs because the Request context is not longer available to the Application_Start event. This blog states two choices to deal with this error:

1) Change your code to work w/o Request, or
2) Modify your application to run in Classic Mode (not recommended).

To get the ApplicationPath, use HttpRuntime.AppDomainAppVirtualPath.



Related Topics



Leave a reply



Submit