Dismissile
Dismissile

Reputation: 33071

MVC Routes - Avoid multiple URLs for the same location

The default route in ASP.net MVC is the following:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

This means that I can reach the HomeController / Index action method in multiple ways:

http://localhost/home/index
http://localhost/home/
http://localhost/

How can I avoid having three URL's for the same action?

Upvotes: 3

Views: 986

Answers (3)

BritishDeveloper
BritishDeveloper

Reputation: 13379

I don't suppose you are doing this for SEO? Google penalises you for duplicate content so it is worthy of some thought.

If this is the case routing is not the best way to approach your problem. You should add a canonical link in the <head> of your homepage. So put <link href="http://www.mysite.com" ref="canonical" /> in the head of your Views/Home/Index.aspx page and whatever url search engines access your homepage from, all SEO value will be attributed to the url referenced in the canonical link.

More info: about the canonical tag

I wrote an article last year about SEO concerns from a developer perspective too if you are looking at this kind of stuff

Upvotes: 0

Kevin LaBranche
Kevin LaBranche

Reputation: 21098

You are seeing the default values kick in.

Get rid of the default values for controller and action.

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new {id = UrlParameter.Optional } // Parameter defaults
    );

This will make a user type in the controller & action.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039528

If you want only:

http://localhost/

then:

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

If you want only:

http://localhost/home/

then:

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

and if you want only:

http://localhost/home/index

then:

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

Upvotes: 4

Related Questions