ASP.NET and Retrieving Different Sections of the Current URL using Request.Url

While working on a project in ASP.NET, I needed a function that would retrieve the domain of the current url, however, I also wanted the function to also retrieve the correct ASP.NET development web server path when developing in Visual Studio. After consulting Google, I ran into this old post on Rick Strahl’s blog about the Request.Url object.

After some experimenting, I created a web page in ASP.NET 2.0 that showed what parts of the URL could be returned using different calls. Consult the following in the page load event.

    protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Request.Url.AbsolutePath= " + Request.Url.AbsoluteUri);
Response.Write("<br>");
Response.Write("Request.Url.AbsoluteUri= " + Request.Url.AbsoluteUri);
Response.Write("<br>");
Response.Write("Request.Url.GetLeftPart(UriPartial.Authority)= " + Request.Url.GetLeftPart(UriPartial.Authority));
Response.Write("<br>");
Response.Write("Request.Url.GetLeftPart(UriPartial.Path)= " + Request.Url.GetLeftPart(UriPartial.Path));
Response.Write("<br>");
Response.Write("Request.Url.GetLeftPart(UriPartial.Scheme)= " + Request.Url.GetLeftPart(UriPartial.Scheme));
Response.Write("<br>");
Response.Write("Request.RawUrl= " + Request.RawUrl);
Response.Write("<br>");
Response.Write("Request.Path= " + Request.Path);
Response.Write("<br>");
Response.Write("Request.ApplicationPath= " + Request.ApplicationPath);
Response.Write("<br>");
Response.Write("Request.ResolveUrl= " + ResolveUrl("~/dealer/default.aspx"));
Response.Write("<br>");
Response.Write("GetAuthorityApplicationPath= " + GetAuthorityApplicationPath());
}

private String GetAuthorityApplicationPath()
{
return String.Concat(Request.Url.GetLeftPart(UriPartial.Authority), Request.ApplicationPath);
}

The function GetAuthorityApplicationPath() is what I needed in the end to dynamically retrieve either the domain in a production environment or the development web server url while running Visual Studio (eg. ‘http://localhost:1234/WebDirectory’)

Leave a Reply