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.
6 Comments
Try Page.PreviousPage and Page.Request.UrlReferrer.
It’s been a while since I looked at it but wouldn’t the IsCrossPagePostBack and PreviousPage properties accomplish this? http://msdn.microsoft.com/en-us/library/system.web.ui.page.iscrosspagepostback.aspx
HttpRequest actually has a UrlReferrer property that returns a Uri, accounting for relative and empty header values.
And depending on your design, you might also want to ensure the request is actually a POST and/or compare the Query/Fragment.
I’d never noticed Uri.Compare – handy!
Cheers ~
Keith
Is Page.IsCrossPagePostback not working out?
http://msdn.microsoft.com/en-us/library/system.web.ui.page.iscrosspagepostback.aspx
Thanks for the notes guys. I hadn’t seen Page.PreviousPage or Request.UrlReferrer (but both map back to the same place that I got my values – i.e. the HttpHeader)
I also hadn’t seen Page.IsCrossPagePostBack (tells you how easy it is to get blinded by what you’re doing.)
Thanks again. – Rob
I had to look into this more. As it turns out Page.PreviousPage applies only to situations where Server.Transfer is used. And in the situation that I’m in with trying to check things in the SharePoint workflow association process the Page.IsCrossPagePostBack returns false.