What is the best solution to URL Rewriting in .NET 4. I’m looking for an easy solution to rewrite URLs like
“myurl.com/ApplicationName/Kohls” to something like “myurl.com/ApplicationName/index.html?store=Kohls” so I can access the var “Kohls” through the Query String.
I am currently using the Global.asax and it has been working for the above case – but I am running into trouble in the case where the user would enter myurl.com/Application, with no “/” or anything after Application.
I currently have this:
protected void Application_BeginRequest(object sender, EventArgs e)
{
String CurrentURLPath = Request.Path.ToUpper();
Match nothingAfterRoot = Regex.Match(CurrentURLPath, @"/ApplicationName(/)?$", RegexOptions.IgnoreCase);
if (nothingAfterRoot.Success)
{
HttpContext myContext = HttpContext.Current;
myContext.RewritePath("/ApplicationName/Default.aspx?store=ABC");
}
else
{
Match match = Regex.Match(CurrentURLPath, @"/ApplicationName(/)?(\w)*$", RegexOptions.IgnoreCase);
if (match.Success)
{
CurrentURLPath = CurrentURLPath.Trim('/');
String store= CurrentURLPath.Split("ApplicationName/".ToCharArray())[1];
HttpContext myContext = HttpContext.Current;
myContext.RewritePath(String.Format("/ApplicationName/Default.aspx?store={0}", store));
}
}
}
Use MVC framework if you have the option. The URL rewriting is the default.
For traditional asp.net sites, I use the UrlRewritingNet.UrlRewriter.dll with the following to my web.config file: