Tuesday, April 28, 2015

ASP.NET C# Using Request.Url and Request.ApplicationPath to get your web application's Base Url

If you ever need to get the base domain and application path of your web application, here is a BasePage property that I use regularly.

Code:
     public string BaseUrl  
     {  
       get  
       {  
         // variables  
         string Authority = Request.Url.GetLeftPart(UriPartial.Authority).TrimStart('/').TrimEnd('/');  
         string ApplicationPath = Request.ApplicationPath.TrimStart('/').TrimEnd('/');  
   
         // add trailing slashes if necessary  
         if (Authority.Length > 0)  
         {  
           Authority += "/";  
         }  
   
         if (ApplicationPath.Length > 0)  
         {  
           ApplicationPath += "/";  
         }  
   
         // return  
         return string.Format("{0}{1}", Authority, ApplicationPath);  
       }  
     }  

I like this technique because whether you are using a virtual directory or not, and whether you are using http or https, you can get the base url easily if you need to build a fully-qualified-url withing your application (e.g. sharing a link, sending an email with a link back, etc).

Example output for a top-level site:
http://dev.sandbox.com/

Example output for a virtual directory:
http://dev.sandbox.com/qa/

Matt Pavey is a Microsoft Certified software developer who specializes in ASP.Net, VB.Net, C#, AJAX, LINQ, XML, XSL, Web Services, SQL, jQuery, and more. Follow on Twitter @matthewpavey

0 comments: