ASP.NET MVC Routing and Slug Like URLs
Currently I'm using a custom class for converting paths to lower case variants, which works without a hitch
Ex. ~/Services/Catering => ~/services/catering
My question is how can I go about getting MVC to correctly parse a URL if I replace the Pascal Case with a more slug like setup
Ex. ~/Services/FoodAndDrink => ~/services/food-and-drink
I generate the URLs in my inherite开发者_如何学God Route class, overriding the GetVirtualPath() function to do the conversion to lowercase and replacing capital letters with a dash and lowercase variant.
I imagine I would have to intercept the URL and just remove the dashes before the routing actually occurs, but I'm not sure where this goes down in the MVC page cycle
Figured it out. Remembered from a previous project when I had to do URL rewriting. Implement the Application_BeginRequest method in the Global.asax.cs file (whatever the class happens to be), do some checking to make sure you rewrite the correct paths, and then use the Context.RewritePath() method
EDIT: Since code was asked for...
public class MvcApplication : System.Web.HttpApplication
{
//---snip---
protected void Application_BeginRequest(object sender, EventArgs e)
{
var url = RewriteUrl(Request.Path);
Context.RewritePath(url);
}
//---snip---
private string RewriteUrl(string path)
{
if (!path.Contains("Content") && !path.Contains("Scripts"))
{
path = path.Replace("-", "");
}
return path;
}
}
精彩评论