AttributeRouting:基于用户角色的多条路由

时间:2015-01-12 11:31:17

标签: asp.net-mvc-5

谢谢你的回复, 我像这样在基本控制器中添加了BeginExecuteCore  `public class BaseController:Controller     {         protected override IAsyncResult BeginExecuteCore(AsyncCallback callback,object state)         {             // string email = string.Empty;             dbEntities dbcontext = new dbEntities();

        var userRoleName = (from n in dbcontext.VAgentClientEmails where n.Email == User.Identity.Name select n.Role).FirstOrDefault();

        if (userRoleName == "SuperAdmin")
            RouteData.Values["role"] = userRoleName;

        else 
            RouteData.Values["role"] = "";

        return base.BeginExecuteCore(callback, state);
    }`

我已经在这样的家庭控制器中给出了

[Route("~/{role}/SavedSearch/Index")] public ActionResult Index() { ... }

为admin / savedsearch / index工作 如果我给fjsdfk / savedsearch / index它的工作 在上述情况下它不应该工作..

而在其他情况下我不想要角色

我需要做任何改变吗?

1 个答案:

答案 0 :(得分:0)

将用户角色添加到url define route中,如下所示:

[Route("~/{role}/propertysearch/Index")]
public ActionResult Index()
{
    // ...
}

并将此方法添加到控制器。当控制器开始执行时,用户角色将添加到用户:

protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
    var userRoleName = //GetUserRoleName;
    RouteData.Values["role"] = userRoleName;
    return base.BeginExecuteCore(callback, state);
}

在这种情况下,网址将如下:

管理员/ propertysearch /索引

用户/ propertysearch /索引

otherMemberRoleName / propertysearch /索引

对于整个应用程序添加控制器并将其命名为BaseController,然后将BeginExecuteCore方法添加到Basecontroller

public class BaseController : Controller
{
    protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
    {
        var userRoleName = //GetUserRoleName;
        RouteData.Values["role"] = userRoleName;
        return base.BeginExecuteCore(callback, state);
    }
}

所有其他控制器都继承BaseController形式:

public class HomeController : BaseController 
{
    [Route("~/{role}/propertysearch/Index")]
    public ActionResult Index()