简体   繁体   中英

MVC4's mapRoute URL — {controller}/{action} vs Controller/{action}. What's the difference?

I recently got burned by the fact that these two MVC4 routes, apparently, function differently. I was wondering if someone could highlight what's going on so I could better understand.

routes.MapRoute(
    "post-User",
    "User",
    new { controller = "User", action = "create" },
    new { httpMethod = new HttpMethodConstraint("POST") }
    );

routes.MapRoute(
    "post-User",
    "{controller}",
    new { controller = "User", action = "create" },
    new { httpMethod = new HttpMethodConstraint("POST") }
    );

I thought that the {controller} bit was a placeholder and that saying controller = "User" in the next line would make these two statements equivilant. Apparently using {controller} sets up defaults for all routes?

You are correct in your belief that the {controller} substring acts as a placeholder for a controller name. With that in mind, then, the following route will match any controller, but default to the User controller where no controller is specified:

routes.MapRoute(
    "post-User",
    "{controller}",
    new { controller = "User", action = "create" },
    new { httpMethod = new HttpMethodConstraint("POST") }
);

The following, however, will match the route User and - because no controller can be specified - will always route to the User controller:

routes.MapRoute(
    "post-User",
    "User",
    new { controller = "User", action = "create" },
    new { httpMethod = new HttpMethodConstraint("POST") }
);

In this instance the difference is meaningless because all you're doing is forcing the route User to map to a controller User , which is exactly what will happen in your first route anyway.

However, consider the following:

routes.MapRoute(
    "post-User",
    "User/{action}",
    new { controller = "User", action = "MyDefaultAction" },
    new { httpMethod = new HttpMethodConstraint("POST") }
);

routes.MapRoute(
    "foo",
    "{controller}/{action}",
    new { controller = "User", action = "Index" },
    new { httpMethod = new HttpMethodConstraint("POST") }
);

Now, your top route will match requests to the User controller, with an optional action specified and will default to MyDefaultAction . Requests to any other controller will not match the first route - because the route does not begin with the constant string User - and will default back to the second route (foo). Again, the action is optional; however, now, unlike the requests to the User controller, your default action for other controllers will be the Index action.

So now...

.../User defaults to the MyDefaultAction action.

.../SomeOtherController defaults to the Index action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM