MyDaftQuestions
MyDaftQuestions

Reputation: 4691

Routes in MVC4 ASP.NET

I'm struggling with Routes in MVC4

I have Home as the controller and I have an Index. I believe a very typical set up! When I load the site from Visual Studio, it runs fine.

Now, I want to understand the routes. To do, I've tried to change the only route there is which is

routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}",
        defaults: new { controller = "Home", action = "Index" }
        ); 

What I don't understand is why does this route not work. I only have 1 controller, which is Home, so by setting Home/{action}/ matches the pattern (although it obviously doesn't)

routes.MapRoute(
        name: "Home",
        url: "Home/{action}/",
        defaults: new { controller = "Home", action = "Index" }
        );

Instead of getting the web page I get the following

HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.
A default document is not configured for the requested URL, and directory browsing is not enabled on the server.

Upvotes: 0

Views: 40

Answers (1)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

You are removing the default route, so there is no longer any route to handle the "/" route.

If you type in yoursite/Home or /Home/Index it will work. But since there is no longer any route to handle the default case, you get this issue.

What you want is to add an additional route, before your default route which does what you want. However, in this case it won't do anything different from the default route when you explicitly enter the /Home url. also, remove the trailing '/' off the url, as i'm not sure if that will cause problems. ie:

routes.MapRoute(
    name: "Home",
    url: "Home/{action}",
    defaults: new { controller = "Home", action = "Index" }
    );
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}",
    defaults: new { controller = "Home", action = "Index" }
    ); 

Upvotes: 2

Related Questions