Posted by
Robert L. Bogue
on
Thursday, 16 Jul 2009 08:50
| 6 Comments |
Every once in a while I'm surprised by what I don't know. I have been developing in ASP.NET for a while and I've known about Page.IsPostBack to determine whether this is the first request to the page (thus I need to populate controls). However, I had never realized that there was a scenario where this didn't work. It doesn't work when you have another page post to your page. The property sees that it's a POST HTTP request and says "Hey, it's a postback!" -- of course in the scenario when it's another page that's doing the posting this doesn't work so well. So I put together a simple function to use the referrer to figure that out.
public static bool IsFirstRequestToPage()
{
HttpRequest curReq = HttpContext.Current.Request;
string referer = curReq.Headers["Referer"];
if (string.IsNullOrEmpty(referer)) // not present - should be present on postback
{
return (true);
}
else
{
// Is referrer current page?
Uri curPage = curReq.Url;
Uri refPage = new Uri(referer);
if (Uri.Compare(curPage, refPage,
UriComponents.SchemeAndServer |
UriComponents.Path,
UriFormat.UriEscaped,
StringComparison.InvariantCultureIgnoreCase) == 0)
{
// Same referrer (i.e. postback)
return false;
}
else
{
// Different referer
return true;
}
}
}
Of course, using the referer header is bad because there are scenarios where it won't be transmitted and some browsers that won't transmit it, etc., but in my case it works well enough.