Here's a question that I've quite a few times over the years and that takes me a minute to remember myself every time I try to use a static Default document in an ASP.NET MVC application - as I often do for demos.
Suppose you have a static index.htm page in your project, have IIS configured to include index.htm as your default document (as it is by default) and you want it to come up when the browser navigates to the default url of your site or virtual directory. Now when you create a new empty or basic MVC project and leave everything set at the default settings and you go to:
http://localhost:30735/
you'll unpleasantly find:
So why is IIS not finding your default resource? The file exists and using:
http://localhost:30735/index.htm
works, so what's the deal?
ASP.NET MVC takes over URL management and by default the routing is such that all extensionless URLs are controlled by the extensionless Url handler defined in web.config:
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
This handler routes all extensionless URLs into ASP.NET's routing mechanism which MVC then picks up to define its internal route handling. Since
http://localhost:30735/
is an extensionless URL it's treated like any other MVC routed URL and tries to map to a configured routing endpoint/controller action. ASP.NET MVC tries to map the URL to a controller and action, and if the default routing is in place it'll try to find the HomeController and the Index action on it. If that exists it'll display, otherwise the above 404 and corresponding error page shows up.
To display a static default page for the root folder there's luckily an easy way to accomplish the task by using routes.IgnoreRoute(""):
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
The routes.IgnoreRoute("") ensures that the default route is ignored and that your index.htm file is found by IIS's default document handling as MVC ignores the route and lets IIS do its thing.
Alas your index.htm page is now served.
Other Posts you might also like