Get a page's current URL

Topics: Controls
May 18, 2009 at 3:32 PM

I've got a website built with BlogEngine that consists of mostly pages, not posts.  I'm trying to modify the PageList.cs file to set a different style for a link if that link represents the current page.  No matter what I do to get the URL or Title of the current page, I get that of some arbitrary page.  Here's what I've got, within the foreach loop in BindPages():

. . . 

System.Web.UI.Page pg = (System.Web.UI.Page)HttpContext.Current.CurrentHandler; string title = pg.Title; 

if (title == page.Title)
  li.Attributes.Add("class", "active");

. . . 

I've tried using "HttpContext.Current.Request.Url" and every other standard way of getting the URL as well.  What is displayed in the address bar is the correct URL for the page; what is assigned to the title variable is the URL for one of the pages -- seems to be arbitrary, cause it changes whenever I make a change to PageList.cs and refresh.

The PageList control is being displayed in site.master, and I've even tried putting it in Page.aspx.  This is definitely strange behavior, and seems like a bug.

Coordinator
May 18, 2009 at 8:13 PM

The BindPages function in the PageList.cs control is only called the first time the blog is visited.  After that first call, the content for the PageList control is cached in memory (in the _Html variable).

There's two things you'll want to do.

1. Change the "Html" property so it doesn't use the _Html variable to cache the page list content.  It should look like:

private string Html
{
  get
  {
      HtmlGenericControl ul = BindPages();
      System.IO.StringWriter sw = new System.IO.StringWriter();
      ul.RenderControl(new HtmlTextWriter(sw));
      return sw.ToString();
  }
}

2. Relying on the Page title isn't reliable.  Especially since Page.Title often contains the name of your blog in it (depending on your settings).  Request.Url usually won't work either because that will usually be a re-written URL that doesn't match the original URL the person requested.  You'll instead want to use RawUrl in the BindPage() function:

if (page.RelativeLink.ToString().Equals(HttpContext.Current.Request.RawUrl, StringComparison.OrdinalIgnoreCase))
{
    li.Attributes.Add("class", "active");
}

May 18, 2009 at 8:28 PM

Thanks--that worked.  The use of the private variable should have clued me in to what was happening there.