URL rewriting in ASP.NET web applications (www.jankoatwarpspeed.com)
published 1 year, 5 months ago, submitted by
janko(2555) 1 year, 5 months ago
So, you hate such URLs
Or you'll hate it after you realize how easy it is to make it nicer. Besides all, URL rewriting will improve your rankings on search engines. Search engines like Google will easily index your "static" URLs, instead of dynamic URLs.
There are several ways to accomplish URL Rewriting. I'll explain how to do this by using HttpModule and how to overcome the postback bug that is the outcome of URL rewriting.
Suppose you have a content management system that stores entire pages in the database. So you can have a Home page, and Home page can have sections Products and Services, and each one of these can have their own child pages or sections, and so on.
So we want dynamic URL like this: Default.aspx?SectionID=5&ItemID=22 to look like /catalogue/furniture/chairs/chair5.aspx or whatever the business logic requirement is.
In the example in this article I will not use a database in order to keep it simple, but you imagine there is a database that keeps the URL for each page. I'll use hard-coded Dictionary that will keep some sample pages.
Note: You can download the full code in the attachment.
First, we'll make a data access object that will search the database for requested url and return its dynamic url. These are the methods in SampleDAO that will simulate the database and getting the url from there:
public string GetRealPath(string requestedUrl)
{
string path = "";
Dictionary<string, string> paths = GetPathsFromDatabase();
if (paths.ContainsKey(requestedUrl))
paths.TryGetValue(requestedUrl, out path);
return path;
}
private static Dictionary<string, string> GetPathsFromDatabase()
{
Dictionary<string, string> paths = new Dictionary<string, string>();
paths.Add("/URLRewrite/FirstSection/Default.aspx".ToLower(), "/URLRewrite/Default.aspx?SectionID=1");
paths.Add("/URLRewrite/SecondSection/Default.aspx".ToLower(), "/URLRewrite/Default.aspx?SectionID=2");
paths.Add("/URLRewrite/FirstSection/Page1.aspx".ToLower(), "/URLRewrite/Default.aspx?SectionID=1&Item=1");
paths.Add("/URLRewrite/FirstSection/Page2.aspx".ToLower(), "/URLRewrite/Default.aspx?SectionID=1&Item=2");
paths.Add("/URLRewrite/SecondSection/Page1.aspx".ToLower(), "/URLRewrite/Default.aspx?SectionID=2&Item=1");
paths.Add("/URLRewrite/SecondSection/SubSection/AnotherOne/Page5.aspx".ToLower(), "/URLRewrite/Default.aspx?SectionID=2&Item=5");
paths.Add("/URLRewrite/Default.aspx".ToLo
|
category: ASP.NET
|
Views: 290
tags:
ReadIt ASP.NET another
Everyones tags:
Your Tags: