2013-01-22 81 views
3

我想編寫一個只適用於某些文件類型的catchall路由。現在我有對特定文件類型的路由約束

routes.MapRoute("Template", "{*path}", new {controller = "Template", action = "Default"}); 

在我的其他路線的底部。這適用於捕捉所有內容。不過,我還有一些其他遺留文件擴展名我想忽略,所以暫時我需要這個最終路徑才能觸發.html文件。

我可以申請嗎?

回答

3

我想出了一些東西。請享用。

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"}) });