我想出了一些東西。請享用。
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"}) });