Adding statics pages to RouteTable and Handle static requests in .Net Mvc


If you have static pages (html) in your .Net Mvc application, you might want to add them to RouteTable or handle request for statics.

Adding static pages to RouteTable

In foo folder if you have bar.html your url will be

example.com/foo/bar.html 

And we want to change with :

 example.com/foo-bar

First add build providers in your web.config for .html and .htm extensions.

(we will add only html pages in this article)

<compilation debug="true" targetFramework="4.5.1"">
      <buildProviders >
        <add extension=".htm" type="System.Web.Compilation.PageBuildProvider" >
        <add extension=".html" type="System.Web.Compilation.PageBuildProvider">
      <buildProviders>
 <compilation>  

And in RegisterRoutes method add your custom routes above default routes.

void RegisterRoutes(RouteCollection routes)

{

 routes.MapPageRoute("", “foo-bar", “~/foo/home.html");

 

            routes.MapRoute(

                name: "Default",

                url: "{controller}/{action}",

                defaults: new { controller = "Home", action = "Index" }

            );

}

Handle request for statics pages.

Sometimes you need to handle request for static pages. The statics are not in .Net pipeline so they serv not in Mvc application. So you can not handle incomming request.

In .Net Mvc aplication controllers are responsive for requests. But static files are not in .Net pipeline. So you can not handle static request on controllers.

Step 1 - Add UrlRoutingModule-4.0 mapping to web.config

The UrlRoutingModule class matches an HTTP request to a route in an ASP.NET application. The module iterates through all the routes in the RouteCollection property and searches for a route that has a URL pattern that matches the format of the HTTP request.

<modules>
  <remove name="UrlRoutingModule-4.0" />
  <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />   
</modules>

Step 2 - Add handler mapping to web.config

<System.Web>
<handlers>
<add name="HtmlFileHandler" path="*.html" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

</handlers>
</System.Web>

Step 3 - Handle incomming request on Application_BeginRequest method

Application_BeginRequest is a event handler. And it executes on all request in runtime.

We want to handle incomming request for /foo/bar.html.

In global.asax.

protected void Application_BeginRequest(object sender, EventArgs e)
{
    if (Request.Headers["X-Requested-With"] != “XMLHttpRequest") // filter xhr requests.
    {
        if (Request.RawUrl.ToLower().Contains("foo/bar.html"))
            // do something
    }
}

References


MSDN - https://msdn.microsoft.com/en-us/library/system.web.routing.urlroutingmodule.aspx

AspNet Mvc 04-06-15