MVC Route路由

由于某些原因,需要默认区域,所以需要对路由进行设置

具体实现如下:

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Qxun.Web.WeScene101.Areas.Mobile
{
    public class MobileAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Mobile";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Mobile_default",
                "{controller}/{action}/{id}",//去掉区域设置mobile,这样匹配的时候,根据controller重写的匹配方法,就能筛选出区域是mobile的了,不过controller可不能和screen排除的一样,要不然就进到screen的区域路由里面去了
                new { action = "Index", id = UrlParameter.Optional, controller = "Home" }
                 , new { controller = new ControllerConstraint() }
            );
        }



    }
    /// <summary>
    /// 设置默认的区域,使用命名空间system.web。继承IRouteConstraint,重写比较方式
    /// </summary>
    public class ControllerConstraint : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
      //获取controller的值
            var value = values["controller"].ToString().ToLower();
            //只能拿到false的情况,排除掉false的,即都是属于区域mobile的了
            if (value.Equals("screen"))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}

 

posted @ 2016-06-22 10:38  Danlis  阅读(343)  评论(0编辑  收藏  举报