ASP.Net MVC 身份验证 - 根据角色隐藏视图中的元素

2024-02-24

是否有可能将Authorize-Attribute的Result交给View?

假设我想根据用户的成员身份在索引视图中隐藏 5 个链接。

[Authorize(Roles = "Admin")]
public ActionResult Index(){
    ....
}

上面的代码将阻止所有不属于管理组的用户访问索引页面。

@{
    if(User.IsInRole("Admin"){
        <a href="#">Some link to be hidden</a>
    }
}

如果用户不属于管理员角色,此代码将隐藏链接。这基本上就是我想要的,但是使用这种方法,如果角色发生变化,我必须更改每个隐藏链接上的角色名称。

难道没有类似两者的结合吗? (架构见下)

[Authorize(Roles = "Admin")] //This will pass true to the View if the User is a member of the group "Admin"
public ActionResult Index(){
    ....
}

@{
    if(User.IsAuthenticated){ //This will read the "Token" and if it's true the if statement will get executed.
        <a href="#">Some link to be hidden</a>
    }
}

因此,如果用户的角色为“管理员”,则会显示链接。这可能吗?


你可以使用ViewBag and ViewData除其他外,但我建议将模型传递回视图,并使用指示是否显示链接的属性。

public class YourViewModel()
{
    public bool ShowHiddenLinks { get; set; }
    // ... whatever other properties
}

在你的控制器中你可以这样做:

[Authorize(Roles = "Admin")] 
public ActionResult Index()
{
    var yourVm = new YourViewModel();
    yourVm.ShowHiddenLinks = true;

    return View(yourVm);
}

你的观点变成:

@model YourViewModel

/* ShowHiddenLinks is true & this view is meant for admins only,
   so show admin-related links */
@if (Model.ShowHiddenLinks)
{
    <a href="#">Some link to be hidden</a>
}

我已命名 viewmodel 属性ShowHiddenLinks故意的,以便它也可以重复用于其他用户的视图。当然,您可以将视图模型扩展到其他角色的功能属性(例如,管理员和版主可以访问的视图,每个视图都有自己独特的一组隐藏链接),或者为每个角色创建一个视图模型 - 这一切都取决于场景。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.Net MVC 身份验证 - 根据角色隐藏视图中的元素 的相关文章

随机推荐