Leo Vo
Leo Vo

Reputation: 10330

Routing on same URL in MVC4

I'm writing a route for area but I got a problem on same URL. This is my web structure:

Project Authentication:
AccountController 
|__SignIn

Project Account: 
AccountController 
|__ChangePassword

I write routes:

First route in AccountAreaRegistration:

context.MapRoute(
    "Account_Default",
    "Account/{action}/{id}",
    new
    {
        controller = "Account",
        id = UrlParameter.Optional
    },
    new[] { "MyProject.Account.Controllers" });

Second route in AuthenticationAreaRegistration:

context.MapRoute(
    "Authentication_Account",
    "Account/SignIn",
    new
    {
        controller = "Account",
        action = "SignIn",
        id = UrlParameter.Optional
    },
    new[] { "MyProject.Authentication.Controllers" });

First route is more priority than second route because AccountAreaRegistration is called before AuthenticationAreaRegistration.

When I open URL: ~/Account/SignIn -> I get error Resource not found because this URL match with first route. How to solve my problem. Thanks.

Upvotes: 0

Views: 86

Answers (2)

sergik
sergik

Reputation: 111

If you are happy to modify the route templates you can do this:

   public override void RegisterArea(AreaRegistrationContext context) 
    {
        context.MapRoute(
            "Authentication_Account",
            "Authentication/SignIn",
            new
            { 
                controller = "Account",
                action = "SignIn",
                id = UrlParameter.Optional
            },
            new[] { "MyApp.Areas.Authentication.Controllers" });
    }

which is modifying only your "Authentication_Account" template and that will let you use ~/Authentication/SignIn and ~/Account/ChangePassword to access your actions - simply making urls unique.

If that's not good enough you can call route registration functions in a different order, so that the more specific route is registered first - in your case that is "Authentication_Account" route. you will need to call them manually, not using RegisterAllAreas in your Global.asax

Upvotes: 1

Bayu Alvian
Bayu Alvian

Reputation: 171

you want the same prefix url like Account/.../.. for different area? i don't think that is the best practice, but if you really want it, you can cut the second route and paste it before the first route. and let your AuthenticationAreaRegistration MapRoute empty.

so your AccountAreaRegistration would be like this:

context.MapRoute(
"Authentication_Account",
"Account/SignIn",
new
{
    controller = "Account",
    action = "SignIn",
    id = UrlParameter.Optional
},
new[] { "MyProject.Authentication.Controllers" });
context.MapRoute(
"Account_Default",
"Account/{action}/{id}",
new
{
    controller = "Account",
    id = UrlParameter.Optional
},
new[] { "MyProject.Account.Controllers" });

Upvotes: 1

Related Questions