Xerratus
Happily stressed out, since 1974


 
Wednesday, August 01, 2007
<< Moving to Portland? Need a house with a great view?
Windows update KB938979 disables systems icons from displaying in the task bar >>

In my years of programming, I've always found one thing that's been fairly consistent; developers love to put the baseUrl in the web.config.  While this is nice and works well good, it does pose it's problems especially in local development environments where the baseUrl isn't always the same.  One day a while back, I decided to write something that grabbed the baseUrl from the Request object.  It didn't take much time at all and works great. 

Today I needed to use it again for another project and thought I'd share while I had it open.

For those of you interested, here is the method I created:

private string GetBaseUrl()
{
    
HttpContext context = Context;
    
string url = context.Request.Url.AbsoluteUri;
    
string baseUrl = url.Replace(context.Request.Url.AbsolutePath, "") + context.Request.ApplicationPath;
    
    
return (baseUrl.EndsWith("/")) ? baseUrl : baseUrl + "/";
}

To use, simply place this into the application_start event:

this.Application.Add("BaseUrl", GetBaseUrl());

Now, to use from within your sites codebase you can access it as such:

string baseUrl = (string)Page.Application["BaseUrl"];

No web.config to worry about and works with different IIS settings when developers are working with the code.

Saturday, August 04, 2007 10:28:10 AM (Pacific Standard Time, UTC-08:00)
Hello John,

One sugestion: just save the scheme and host name and add the app path to that. This way you can also deal with the www vs. non www problem by doing a 301 when you need to.
Adi
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview