使用 ASP.NET 路由来提供静态文件
可以使用 ASP.Net 路由(不是 MVC)来提供静态文件吗?
Can ASP.Net routing (not MVC) be used to serve static files?
说我想路由
http://domain.tld/static/picture.jpg
到
http://domain.tld/a/b/c/picture.jpg
而且我想动态地进行,因为重写的 URL 是即时计算的.我无法一劳永逸地设置静态路由.
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())
);
在 FileRouteHandler.ProcessRequest
方法中,我可以将路径从 /static/picture.jpg
重写为 /a/b/c/picture.jpg代码>.然后我想为静态文件创建一个处理程序.ASP.NET 为此使用
StaticFileHandler
.不幸的是,这个类是内部的.我尝试使用反射创建处理程序,它确实有效:
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);
但是使用内部类型似乎不是正确的解决方案.另一种选择是实现我自己的 StaticFileHandler
,但正确执行此操作(支持范围和 etag 等 HTTP 内容)并非易事.
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.
我应该如何处理 ASP.NET 中静态文件的路由?
How should I approach routing of static files in ASP.NET?
在研究这个问题几个小时之后,我发现只需添加忽略规则就可以为您的静态文件提供服务.
After digging through this problem for a few hours, I found that simply adding ignore rules will get your static files served.
在RegisterRoutes(RouteCollection routes)中,添加以下忽略规则:
In RegisterRoutes(RouteCollection routes), add the following ignore rules:
routes.IgnoreRoute("{file}.js");
routes.IgnoreRoute("{file}.html");