ASP.Net MVC – Resource Cannot be found error

LCJ picture LCJ · Feb 15, 2012 · Viewed 179.7k times · Source

I am completely new to ASP.Net MVC. I just created an MVC3 project in Visual Studio 2010. The view engine is razor. When I just ran the application it gave the proper result in the browser. The URL is http://localhost:4163/ . Then I applied “Set as Start Page” to Index.cshtml inside ~\Views\Home folder. Then when I ran the application the url became http://localhost:4148/Views/Home/Index.cshtml and it said the resource cannot be found. What do I do to correct it? Where is the url mapping done?

Global.asax file:

using System.Web.Mvc;
using System.Web.Routing;

namespace TEST
{

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
    }
 }

Answer

greg84 picture greg84 · Feb 15, 2012

URL mapping or "routing" is handled by Global.asax in the root of your ASP.NET MVC site.

When you click "Set as Start Page" it changes the project settings to look for that file relative to the application root. But in MVC the default route to your index page is actually http://localhost:4163/Home/Index - read something like this to get an idea of how routing works.

To "fix" your project now that it's trying (and failing) to navigate to the view directly, right click the project and choose "Properties", click the "Web" tab and choose "Specific Page", leaving the text box blank. Now when you start to debug it should go to the home page again - look at the default route parameters to see why in the RegisterRoutes method in Global.asax