限制视图的某些部分

时间:2014-12-09 16:36:26

标签: c# asp.net-mvc razor

我有一个组织。在该组织中,您可以拥有多个角色。 (现在只允许其中两个),护士管理员

所以我'保护'我的控制器动作就像这样

[AuthorizeUser(UserRole = "Admin, Nurse", OrganizationType = "Institution")]

我的AuthorizeUser类就像这样

public class AuthorizeUser : AuthorizeAttribute
{
    public String UserRole { get; set; }



    public string OrganizationType { get; set; }
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {
            return false;
        }

        return CheckOrganizationType.checkRole(this.UserRole, this.OrganizationType, Auth.CurrentUser);
    }
}

CheckOrganiztionType函数就像这样

public static bool checkRole(String role, String organizationType, User user)
    {
        RolesType rt = null;
        OrganizationType ot = null;
        foreach (UserRoles ur in user.GetUserRoles())
        {
            rt = RolesType.Get(ur.organizationTypeId,ur.roleTypeId);
            ot = OrganizationType.Get(ur.organizationTypeId, "1");



        }

        if (rt != null && role.Contains(rt.Name) && ot != null && ot.Name == organizationType)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

完美无缺。如果我不是管理员或不是护士,我不允许去这里。

但我想要做的是使用相同的技术控制我视图的某些部分。在互联网上搜索后,我发现了一些我将在下面发布的内容,我希望你们有人对此发表评论。

在我的cshtml文件中,我这样做

@using InstaFood.Helpers
@using InstaFood.Secuirty

@if (CheckOrganizationType.checkRole("Admin", "Institution", Auth.CurrentUser))
{
   <span>Admin</span>
}else{
   <span>Nurse</span>
}

您认为这是正确的方法还是有其他方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

如果您实施自定义RoleProvider,则根据您的域模型为用户提供角色, 然后在您的视图中,您可以使用以下代码:

if (User.IsInRole("Admin")) {
     <span>Admin</span>
}
else {
    ....
}

自定义RoleProvider可在此处找到http://msdn.microsoft.com/en-us/library/317sza4k(v=vs.100).aspx

要注册自定义角色提供者,您必须在configuration / system.web / roleManager配置web.config

<roleManager defaultProvider="OdbcRoleProvider" 
  enabled="true"
  cacheRolesInCookie="true"
  cookieName=".ASPROLES"
  cookieTimeout="30"
  cookiePath="/"
  cookieRequireSSL="false"
  cookieSlidingExpiration="true"
  cookieProtection="All" >
  <providers>
    <clear />
    <add
      name="OdbcRoleProvider"
      type="Samples.AspNet.Roles.OdbcRoleProvider"
      connectionStringName="OdbcServices" 
      applicationName="SampleApplication" 
      writeExceptionsToEventLog="false" />
  </providers>
</roleManager>