【问题标题】:Route constraint to specific file type路由约束到特定文件类型
【发布时间】:2013-01-22 15:19:10
【问题描述】:

我想写一个只适用于某些文件类型的包罗万象的路由。现在我有

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

在我的其他路线的底部。这适用于捕获所有内容。但是,我还有一些其他的遗留文件扩展名我想忽略,所以暂时我需要这条最终路线来仅触发 .html 文件。

有我可以申请的路线限制吗?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-routing url-routing


    【解决方案1】:

    我想通了。享受吧。

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

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      • 2017-08-17
      相关资源
      最近更新 更多