serge
serge

Reputation: 15229

MVC Routing config: URL Pattern with a mixed Segment and defaults

I have the following routing configuration under a MVC sample project:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute("", "X{controller}/{action}",
            new { controller = "Customer", action = "List" });

        routes.MapRoute("MyRoute", "{controller}/{action}",
            new { controller = "Home", action = "Index" });
    }
}

I redirect all controllers (Home, Customer) to the same view that displays the Current controller and action name.

So, for the URL http://localhost:5O44O/XCustomer I have the following output:

The controller is: Customer
The action is: List

I expected that for the URL http://localhost:5O44O/X I should have the same output... But this is not the case...

Server Error in '/' Application.

The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /X

Why that? I placed the "X" condition first, so I should obtain the default replacements with Customer and List ?!

Upvotes: 1

Views: 7058

Answers (1)

Andrey Gubal
Andrey Gubal

Reputation: 3479

You a are receiving 404 error, because you don't have XController. If you have it, you'd receive route: http://localhost:5O44O/XX

routes.MapRoute("", "X{controller}/{action}" - this is just a syntaxis to generete string of route. And it doesn't have a behavior you were expected.

All manipulations should be done here:

new { controller = "Customer", action = "List" });

If you want to have such route: http://localhost:5O44O/X/List you need to write your MapRoute as follows:

routes.MapRoute("name", "X/{action}",
            new { controller = "Customer", action = "List" });

You may even write:

routes.MapRoute("name", "HelloBro",
                new { controller = "Customer", action = "List" });

It will return you route http://localhost:5O44O/HelloBro for your List action of Customer controller

Upvotes: 3

Related Questions