Server.Transfer("product.aspx?ProductID=13");
tblProducts | ||
ProductID | ProductName | ProductPage |
---|---|---|
1 | First Product | firstproduct.aspx |
2 | Second Product | secondproduct.aspx |
3 | Third Product | thirdproduct.aspx |
public class ProductPage : PageNow we have to create our fake pages, inherit them all from the ProductPage class and voi la - that's it! We can also optionally remove all the HTML-code from the aspx-files, leaving the "Page" directive only.
{
private SqlConnection cn;
private SqlCommand cmd;
protected override void OnLoad(EventArgs e)
{
//lets initialize our database connection
//remember to specify the connection string
cn = new SqlConnection(yourConnectionString);
cmd = new SqlCommand();
cmd.Connection = cn;
//determine the page being requested in the browser
string pageFileName = Request.Path.Substring(Request.Path.LastIndexOf("/")+1);
//get the right ProductID from the database
cmd.CommandText = "SELECT ProductID FROM tblProducts WHERE ProductPage=@ProductPage";
cmd.Parameters.AddWithValue("@ProductPage", pageFileName);
cn.Open();
object productID = cmd.ExecuteScalar();
cn.Close();
//if ProductID found
if(productID!=null && productID!=DBNull.Value)
{
//let's transfer the execution
Server.Transfer("product.aspx?ProductID=" + productID.ToString());
}
}
}
namespace URLRewriteNow we have to register our HttpModule in the web.config:
{
public class ProductPageModule : IHttpModule
{
public ProductPageModule()
{
}
public void Dispose()
{
}
public void Init(HttpApplication application)
{
//let's register our event handler
application.PostResolveRequestCache += (new EventHandler(this.Application_OnAfterProcess));
}
private void Application_OnAfterProcess(object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
//the file being requested is not found
if (!File.Exists(application.Request.PhysicalPath))
{
//replace the "newURL"
//with your own value
string newURL = "product.aspx?ProductID=13";
context.RewritePath(newURL);
}
}
}
}
Alex Yumashev
Alex has founded Jitbit in 2005 and is a software engineer passionate about customer support.