Using ASP.NET routing to serve static files

asp.net, url-routing

Solution

After digging through this problem for a few hours, I found that simply adding ignore rules will get your static files served.

In RegisterRoutes(RouteCollection routes), add the following ignore rules:

routes.IgnoreRoute("{file}.js");
routes.IgnoreRoute("{file}.html");

Problem

Can ASP.Net routing (not MVC) be used to serve static files? Say I want to route ``` http://domain.tld/static/picture.jpg ``` to ``` http://domain.tld/a/b/c/picture.jpg ``` and I want to do it dynamically in the sense that the rewritten URL is computed on the fly. I cannot set up a static route once and for all. Anyway, I can create a route like this: ``` routes.Add( "StaticRoute", new Route("static/{file}", new FileRouteHandler()) ); ``` In the `FileRouteHandler.ProcessRequest` method I can rewrite the path from `/static/picture.jpg` to `/a/b/c/picture.jpg`. I then want to create a handler for static files. ASP.NET uses the `StaticFileHandler` for this purpose. Unfortunately, this class is internal. I have tried to create the handler using reflection and it actually works: ``` Assembly assembly = Assembly.GetAssembly(typeof(IHttpHandler)); Type staticFileHandlerType = assembly.GetType("System.Web.StaticFileHandler"); ConstructorInfo constructorInfo = staticFileHandlerType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); return (IHttpHandler) constructorInfo.Invoke(null); ``` But using internal types doesn't seem to be the proper solution. Another option is to implement my own `StaticFileHandler`, but doing so properly (supporting HTTP stuff like ranges and etags) is non-trivial. How should I approach routing of static files in ASP.NET?

Original source

Related problems