【问题标题】:Asp.net MVC3: is really based on roles @Html.Action()Asp.net MVC3:真的是基于角色@Html.Action()
【发布时间】:2013-11-30 17:12:47
【问题描述】:

My View 使用@Html.Action(…) 来反映各种功能块。在打开页面时,站点会为没有在控制器方法中指定角色的用户显示授权对话框。 (例如“经理”或“呼叫者”)按“取消”获得: 401 - 未经授权:由于凭据无效,访问被拒绝。 如果用户没有所需的角色、@Html.Action 被忽略或不显示任何内容,我是否可以更改我的应用程序行为?

我的看法:

@model InApp.ViewModel.ListViewModel
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="CallList">
@Html.Action("List","Call",new {id=Model.id})
</div>

<div class="Order">
@Html.Action("Create","Order",new {id=Model.id})
</div>

控制器:

[Authorize(Roles = "manager, caller")] //if a user is not 'manager' or 'caller'
public PartialViewResult List()        // nothing is shown
{
  //...private 
  return PartialView();
}

[Authorize(Roles = "manager, admin")]
public PartialViewResultCreate()
{
  //...private 
  return PartialView();
}

试图找到正确的解决方案我发现了类似的问题:

Ignore @Html.Action() if user not in Roleasp.net MVC3 razor: display actionlink based on user role 但我不喜欢视图中的“如果”条件。我正在寻找一种复杂的解决方案来仅使用 AuthorizeAttribute 来隐藏和显示单独的部分,并避免在 View 或 Controller 中使用 if – else。感谢您的帮助!

【问题讨论】:

  • 如果您想完全避免 if 语句,也许您可​​以将这些链接(您的视图上的@html.actions)移动到它们各自的局部视图。

标签: c# asp.net asp.net-mvc asp.net-mvc-3 razor


【解决方案1】:

我可以建议使用这种扩展方法:

这是@Html.Action 的包装器,它使用反射检查用户权限。

public static  MvcHtmlString ActionBaseRole(this HtmlHelper value, string actionName, string controllerName, object routeValues , IPrincipal user)
 {     
   bool userHasRequeredRole = false;
   Type t = Type.GetType((string.Format("MyProject.Controllers.{0}Controller",controllerName))); // MyProject.Controllers... replace on you namespace
   MethodInfo method = t.GetMethod(actionName);
   var attr = (method.GetCustomAttribute(typeof(AuthorizeAttribute), true) as AuthorizeAttribute);
   if (attr != null)
   {
      string[] methodRequeredRoles = attr.Roles.Split(',');
      userHasRequeredRole = methodRequeredRoles.Any(r => user.IsInRole(r.Trim())); // user roles check in depends on implementation authorization in you site  
                                                                                            // In a simple version that might look like                                                                         
   }
   else userHasRequeredRole = true; //method don't have Authorize Attribute
   return userHasRequeredRole ? value.Action(actionName, controllerName, routeValues) : MvcHtmlString.Empty; 
 }

在视图中使用:

@Html.ActionBaseRole("List","Call",new {id=Model.id},User)

【讨论】:

    【解决方案2】:

    如果您不喜欢视图中的这种逻辑 - 将其移至其他位置。例如,您可以制作自己的扩展方法并像@Html.ActionOrNothing(...) 一样使用它。

    并且实现应该检查用户是否有权查看某些内容,否则返回一个空字符串/视图。

    【讨论】:

      猜你喜欢
      • 2013-02-13
      • 1970-01-01
      • 2012-02-17
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      • 1970-01-01
      相关资源
      最近更新 更多