Search code examples
c#asp.net-mvcasp.net-mvc-routing

Custom routing ASP.NET MVC


So I want to get my URLs to look something similar to this:

example.com, example.com/contact, example.com/sign-up, example.com/account

Instead of the default MVC way which would look like:

example.com, example.com/Home/Contact, example.com/Account/SignUp, example.com/Account/Account

All HomeController views work fine, but my AccountController doesn't.

When going to example.com/account I get an error saying:

The resource cannot be found.

This is my RouteConfig:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.LowercaseUrls = true;

    routes.MapRoute(
        name: "Default",
        url: "{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        name: "Account",
        url: "{action}/{id}",
        defaults: new { controller = "Account", action = "Account", id = UrlParameter.Optional }
    );
}

And because I wanted to display the Account/SignUp view as /sign-up I added some custom code in the AccountController.

// GET: Account
public ActionResult Account()
{
    return View();
}

// GET: Sign Up
[ActionName("Sign-Up")]
public ActionResult SignUp()
{
    return View("SignUp");
}

Both formats /account or /account/account give me the same error from earlier. However /about, /contact, etc. does not.

Any help is appreciated, thanks!

P.S This is my folder structure:

> Views
-> Account
--> Account.cshtml
--> SignUp.cshtml
-> Home
--> About.cshtml
--> Contact.cshtml
--> Index.cshtml

Solution

  • Route setup would need to be more explicit.

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.LowercaseUrls = true;
    
        routes.MapRoute(
            name: "Account",
            url: "account/{action}/{id}",
            defaults: new { controller = "Account", action = "Account", id = UrlParameter.Optional }
        );
    
        routes.MapRoute(
            name: "Default",
            url: "{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }