RequireOrPermanentRedirect<T>
Use this method to easily check that a required querystring both exists and is of a certain type. This lets you fire off a few checks in your page_load and then write the rest of the code on the page safe in the knowledge that the querystring exists, has a value and can be parsed as the intended data type. If the querystring is not present or is an invalid type the user is sent to the RedirectUrl. Urls starting with a tilde (~) are also supported. This url is normally the next logical level up the tree such as an admin manaagement page, a product index page or if there isn't an appropriate page then you can send the user back to the homepage.
Source
public static void RequireOrPermanentRedirect<T>(this System.Web.UI.Page page, string QueryStringKey, string RedirectUrl)
{
string QueryStringValue = page.Request.QueryString[QueryStringKey];
if (String.IsNullOrEmpty(QueryStringValue))
{
page.Response.Redirect(page.ResolveUrl(RedirectUrl));
}
try
{
T value = (T)Convert.ChangeType(QueryStringValue, typeof(T));
}
catch
{
page.Response.Redirect(page.ResolveUrl(RedirectUrl));
}
}
Example
protected void Page_Load(object sender, EventArgs e)
{
Page.RequireOrRedirect<int>("CategoryId", "~/");
}