有条件的定义路线 [英] Defining conditional routes

查看:127
本文介绍了有条件的定义路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找类似的东西,但没有运气。我想建立一个使用了相同的URL不同的控制器的应用程序。基本思路是这样的,如果一个用户登录,因为他使用管理员可以说管理器,如果用户仅仅是他使用用户控制器的用户。这只是一个例子,基本上我想有一个决定什么控制器航线需要的功能。

I've been searching for something similar but no luck. I want to build an app that uses different controllers for same urls. Basic idea is like that if a user is logged in as admin he uses lets say admin controller, if user is just a user he uses user controller. This is just an example, basically I want to have a function that decides what controller route takes.

感谢大家ü。任何帮助是极大的AP preciated。

Thank u everyone. Any help is greatly appreciated.

PS
利用这个:
管理员拥有不同的用户界面和选项,
输出醒目,
关注的分离

PS Use of this: Admin has different UI and options, Output catching, Separation of concern

推荐答案

您需要创建一个RouteConstraint检查用户的角色,如下所示:

You need to create a RouteConstraint to check the user's role, as follows:

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

namespace Examples.Extensions
{
    public class MustBeAdmin : IRouteConstraint
    {
        public MustBeAdmin()
        { }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
        {
            // return true if user is in Admin role
            return httpContext.User.IsInRole("Admin");
        }
    }
}

那么,你的默认路由之前就宣布了管理员角色的路线,方法如下:

Then, before your default route, declare a route for the Admin role, as follows:

routes.MapRoute(
    "Admins", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Admin", action = "Index", id = UrlParameter.Optional }, // Parameter default
    new { controller = new MustBeAdmin() }  // our constraint
);

counsellorben

counsellorben

这篇关于有条件的定义路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆