Nicolas Cadilhac
Nicolas Cadilhac

Reputation: 4745

Asp.Net MVC routing: best way to have a single element in the URL?

I will take the example of the SO site. To go to the list of questions, the url is www.stackoverflow.com/questions. Behind the scene, this goes to a controller (whose name is unknown) and to one of its actions. Let's say that this is controller=home and action=questions.

How to prevent the user to type www.stackoverflow.com/home/questions which would lead to the same page and would lower the rank of the page as far as SEO is concerned. Does it take a redirect to solve this? Does it take some special routing rules to handle this kind of situation? Something else?

Thanks

Upvotes: 1

Views: 269

Answers (3)

Nick Berardi
Nick Berardi

Reputation: 54864

You want to use the following route. It is really easy you just create a new route that eliminates the need for the controller to be in the route. You create a template string that just contains the action and you default the controller to the controller you want to use such as "Home".

routes.MapRoute(
    "MyRoute",
    "{action}",
    new { controller = "Home", action = (string)null },
    new { action = "[a-zA-z_]+" }
);

Hope this helps.

Upvotes: 1

Craig Stuntz
Craig Stuntz

Reputation: 126577

During Phil Haack's presentation from PDC, Jeff shows some of the source code for Stack Overflow. Among the things he shows is the code for some of the route registrations. He's got these in the controllers, and it's not clear to me that he uses a default route at all. With no default route, you wouldn't need to worry about /home/questions, for example.

As for /questions/index, yes, a permanent redirect is the way to go. You won't get any search engine penalty for a permanent redirect.

Another way to eliminate /home/questions would be to use a route constraint.

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532595

I assumed that the controller was questions and the action was index, i.e., the default action as defined by the route handler. Thus there isn't an alternative path to the page.

Upvotes: 1

Related Questions