【问题标题】:Is it possible to route only specific static files in MVC?是否可以在 MVC 中仅路由特定的静态文件?
【发布时间】:2015-01-18 05:04:59
【问题描述】:
有类似问题的an answer。
但我不想路由所有现有文件 (RouteExistingFiles = true),然后忽略所有我不需要的类型。
我可以更准确地使用 MVC 或 IIS 设置来告诉它我的意图吗?
【问题讨论】:
标签:
asp.net-mvc
asp.net-mvc-routing
static-files
【解决方案1】:
最后,我做了以下方式:
在 RouteConfig.cs 中:
public static void RegisterRoutes(RouteCollection routes)
{
routes.RouteExistingFiles = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*route}", new { route = new AnyExistingFileExceptRazorView() });
...
}
其中AnyExistingFileExceptRazorView 是自定义路由约束:
public class AnyExistingFileExceptRazorView : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,
RouteDirection routeDirection)
{
string filePath = httpContext.Server.MapPath(httpContext.Request.Url.AbsolutePath)
.ToLower();
return File.Exists(filePath)
&& !( filePath.EndsWith(".cshtml") || filePath.EndsWith(".vbhtml"));
}
}
ToLower() 被调用是因为我不确定 URL 的大小写,我检查了预期小写的结尾。
也可以比较Path.GetExtension(fielPath) == ".cshtml";