-
-
Url Rewriting Using RewritePath
by azamsharp on 5/4/2008 8:34:29 PM
-
Here is some code to Rewrite the Urls using the RewritePath method. Please note that in the production this code should be in the HTTP MODULE.
-
public class NewUrl
{
private string _key;
private string _url;
public string Key
{
get { return _key; }
set { _key = value; }
}
public string Url
{
get { return _url; }
set { _url = value; }
}
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
List<NewUrl> routes = new List<NewUrl>()
{ new NewUrl() { Key = "Categories", Url = "~/CodeSubmissionsByCategory.aspx?id=" },
new NewUrl() { Key = "Refactorings", Url = "~/SubmissionDetails.aspx?id=" }
};
HttpContext context = HttpContext.Current;
string oldPath = context.Request.Url.ToString();
var newRoute = (from route in routes
where oldPath.IndexOf(route.Key) > -1
select route).SingleOrDefault();
if (newRoute == null) return;
int i = oldPath.IndexOf(newRoute.Key);
if (i > -1)
{
int underScoreIndex = oldPath.IndexOf("_");
int startIndex = (i + newRoute.Key.Length + 1);
int numberOfCharacters = underScoreIndex - startIndex;
int id = Int32.Parse(oldPath.Substring(startIndex, numberOfCharacters));
context.RewritePath(newRoute.Url + id, false);
}
}
-
Refactor it!
-
no need to recreate the routes each time. Create them in the Application_Start method and keep a static reference to them.
by subdigital on 5/5/2008 7:31:37 AM
-
-
Thanks for the excellent tip!
Maybe also put the route information in web.config file. We can put this in AppSettings or make a custom section for it.
by azamsharp on 5/5/2008 7:59:10 AM
-
-
Now, the problem seems to be fixed!
by azamsharp on 5/5/2008 2:32:21 PM
-
Please log in to refactor the code!
Login