1

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 inherited 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

1 Answer 1

5

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Added the requested code. I actually changed my mind though because creating the slug proved to be rather problematic. It's actually for a mobile site though, so the URL formatting is less important at the moment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.