我想写一个只适用于某些文件类型的包罗万象的路线。现在我有
routes.MapRoute("Template", "{*path}", new {controller = "Template", action = "Default"});
在我其他路线的底部。这适用于捕捉一切。但是,我还有一些其他遗留文件扩展名我想忽略,所以暂时我需要这个最终路径来只触发 .html 文件。
我可以申请这个路线限制吗?
最佳答案
我想通了。享受吧。
using System;
using System.Linq;
using System.Web;
using System.Web.Routing;
namespace Project.App_Start
{
public class FileTypeConstraint : IRouteConstraint
{
private readonly string[] MatchingFileTypes;
public FileTypeConstraint(string matchingFileType)
{
MatchingFileTypes = new[] {matchingFileType};
}
public FileTypeConstraint(string[] matchingFileTypes)
{
MatchingFileTypes = matchingFileTypes;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
string path = values["path"].ToString();
return MatchingFileTypes.Any(x => path.ToLower().EndsWith(x, StringComparison.CurrentCultureIgnoreCase));
}
}
}
用法:
routes.MapRoute(
"Template",
"{*path}",
new {controller = "Template", action = "Default"},
new { path = new FileTypeConstraint(new[] {"html", "htm"}) });
关于asp.net-mvc - 路由约束到特定文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14461881/