zoukankan      html  css  js  c++  java
  • MVC自定义路由02-实现IRouteConstraint限制控制器名


    通过实现IRouteConstraint接口,实现对某个控制名进行限制。本篇把重点放在自定义约束,其余部分参考:

    MVC自定义路由01-为什么需要自定义路由 

      自定义约束前

    using System.Web.Mvc;
    using System.Web.Routing;
    using MvcApplication2.Extension;
     
    namespace MvcApplication2
    {
        public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
     
                //默认
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                );
            }
        }
    }
     

    效果

    约束前

     

      自定义约束后

    □ 实现IRouteConstraint接口

    using System;
    using System.Web.Routing;
     
    namespace MvcApplication2.Extension
    {
        public class ExcludeController : IRouteConstraint
        {
            private readonly string _controller;
     
            public ExcludeController(string controller)
            {
                _controller = controller;
            }
            public bool Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
            {
                //如果路由中拿到的controller值与约束设定的值相等,就返回false
                return !string.Equals(values["controller"].ToString(), _controller, StringComparison.OrdinalIgnoreCase);
            }
        }
    }
     

    □ 路由添加约束

    using System.Web.Mvc;
    using System.Web.Routing;
    using MvcApplication2.Extension;
     
    namespace MvcApplication2
    {
        public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
     
                //默认
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                    constraints: new { controller = new ExcludeController("RentalProperties") }
                );
            }
        }
    }
     

    效果

    约束后

    可见,加上自定义约束后,带RentalProperties名称的控制器将被限制。

  • 相关阅读:
    安装sublime text2 for ubuntu
    ruby中Regexp用法
    rvm is not a function的解决方法
    解决启动mongod 时,出现addr already in use错误
    rails中常用的插件
    在数据库中存储层次数据
    Formtastic: Forms Made Crazy Easy for Rails Developers
    rails安全性
    Rails 增加一个模型(model)
    RPC框架实现思路浅析
  • 原文地址:https://www.cnblogs.com/darrenji/p/3593483.html
Copyright © 2011-2022 走看看