MVC4 mapRoute URL - {controller} / {action} vs Controller / {action}. Who cares?

I recently got burned out due to the fact that these two MVC4 routes seem to function differently. I was wondering if anyone could highlight what is going on so that I can understand better.

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 the {controller} bit was overridden and saying controller = "User" on the next line would make the two statements equal. Obviously using {controller} sets default values โ€‹โ€‹for all routes?

+3


source to share


1 answer


You are correct in your belief that the substring {controller}

acts as a placeholder for the controller name. With that in mind, the following route will match the controller any , but the default is a controller User

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 a route User

and - since no controller can be specified - will always route to a controller User

:

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

      

The difference doesn't make sense in this case, because all you do is force the route to User

map to the controller User

, which will happen on 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 controller requests User

, with the specified optional action, and will default to MyDefaultAction

. Requests to any other controller will not match the first route - because the route does not start with a constant string User

- and will default to the second route (foo). Again, the action is optional; however now, unlike controller requests User

, your default action for other controllers will act like Index

.

So now ...

.../User

the default is the action MyDefaultAction

.

.../SomeOtherController

the default is the action Index

.

+5


source







All Articles