ASP.NET MVC Strange Home Route Behavior
by Dave 11-February-2010
How to Make Sure "/" Always Works
I've run into situations in which ASP.NET MVC apps that redirect to the Home
controller's Index action using <%= Html.ActionLink("Home", "Index", "Home")%>
show a directory listing instead of the
home page. This happens when using the built-in ASP.NET webserver, but it can also occur
in an improperly configured IIS deployment.
In ASP.NET MVC 1.0, to ensure that the MVC app always navigates to the root in URLs
such as http://localhost/myapp (i.e. when the URL is simply the site's root), I
have done the following to avoid this problem:
- In Global.asax.cs, add a route for the default route, which you'll likely already
have:
routes.MapRoute( "Root", "", new { controller = "Home", action = "Index", id = "" } );
- Create a Default.aspx and add this in the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
HttpContext.Current.RewritePath(Request.ApplicationPath, false);
IHttpHandler httpHandler = new MvcHttpHandler(); httpHandler.ProcessRequest(HttpContext.Current);
}
- In your project properties, on the Web tab, set the Start Action to Specific Page,
and choose Default.aspx.
- If your site requires authentication, you'll need to allow access to Default.aspx to
allow this to work:
<location path="Default.aspx">
<system.web> <authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
So... it worked but it seemed like a hack and a half. In ASP.NET MVC 2.0 things seem
a little easier:
- Do NOT have a route for the default route (as above in #1)
- In Default.aspx, redirect to the Index action in the Home controller in Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect("Home/Index");
}
- In the project properties, set Default.aspx as the Start Action, Specific Page setting
- Note that allowing access to Default.aspx in web.config would still seem to apply in cases where
you've locked down the site and require authentication as described above.