码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET MVC自定义路由 - 实现IRouteConstraint限制控制器名(转载)

时间:2015-03-02 22:28:28      阅读:351      评论:0      收藏:0      [点我收藏+]

标签:

自定义约束前

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名称的控制器将被限制。

 

ASP.NET MVC自定义路由 - 实现IRouteConstraint限制控制器名(转载)

标签:

原文地址:http://www.cnblogs.com/gscvery/p/4309774.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!