Click here to Skip to main content
Licence CPOL
First Posted 21 Jul 2007
Views 19,054
Bookmarked 19 times

Adding a base tag to your ASP code dynamically

By | 21 Jul 2007 | Article
How to dynamically add a base tag to your ASP code.

Introduction

When using relative paths in your HTML code, it is helpful to set the base tag. But that base may be different for each developer on your team, or on stage, QA, or production. Also, when making your URL optimized for search engines, your URL will map to a non-existing path. The best way to solve this is by adding the <base href="..."/> tag to the page header dynamically.

Using the code

The solution is quite simple. First, create a new class called BaseTag that has the following code:

public class BaseTag : HtmlControl
{
    public BaseTag(HttpRequest request): base("base")
    {
        base.Attributes.Add("href", 
            request.Url.Scheme + "://" + 
            request.Url.Authority + 
            request.ApplicationPath + "/");
    }
}

The key part is Url.Scheme that returns the URL scheme: such as HTTP and HTTPS. Url.Authority returns the host and port address, if one is provided. Next is the application path that is often unique to the location of the web app directory. Put them all together with the right string construct, and you get a nice well formed href for the base tag like:

http://someurl:8080/web/

Next, include the following line in the Page_Load method of your *.aspx.cs file:

protected void Page_Load(object sender, EventArgs e)
{
    this.Header.Controls.AddAt(0, new BaseTag(Request)); 
}

The end result is the <base href="http://someurl:8080/web/"/> tag.

I hope this is helpful to you.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Grundela2007



United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralAll sorts of problems with base tags [modified] Pinmembertadd7810:42 5 Sep '07  
Questionnot working for master page and control ? Pinmemberfreddoo3:24 31 Jul '07  
GeneralGetLeftPart() Pinmembergrundt7:07 22 Jul '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 21 Jul 2007
Article Copyright 2007 by Grundela2007
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid