ASP.Net MVC身份验证-根据角色在视图中隐藏元素 [英] ASP.Net MVC Authentication - Hide Element in View based on roles
问题描述
是否可以将Authorize-Attribute的结果移交给视图?
Is there a possibility to hand over the Result of the Authorize-Attribute to the View?
假设我要根据用户的成员身份在索引视图中隐藏5个链接.
Let's assume I want to hide 5 links in my Index view based on the memberships of a User.
[Authorize(Roles = "Admin")]
public ActionResult Index(){
....
}
上面的代码将阻止所有不属于Admin-Group的用户访问索引"页面.
The code above will prevent all users that are not part of the Admin-Group from visiting the Index page.
@{
if(User.IsInRole("Admin"){
<a href="#">Some link to be hidden</a>
}
}
如果用户不属于管理员角色,则此代码将隐藏链接.基本上,这就是我想要使用此方法进行的操作,如果角色会发生变化,我必须在每个隐藏链接上更改角色名称.
This code will hide the link if the User is not part of the Admin role. This is basically what I want BUT using this method I have to change the role name on every hidden link if the role would change.
是不是两者兼而有之? (示意图请参见下文)
Isn't there something like a combination of both? (Schema see below)
[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>
}
}
因此-如果用户处于管理员"角色,则将显示链接.这可能吗?
So - if the User is in Role "Admin" the link will be shown. Is this possible?
推荐答案
您可以使用ViewBag
和ViewData
等方法,但是我建议将模型传递回具有指示是否显示该属性的属性的视图.链接与否.
You could use ViewBag
and ViewData
among other things, but I'd suggest passing a model back to the view with properties indicating whether to display the links or not.
public class YourViewModel()
{
public bool ShowHiddenLinks { get; set; }
// ... whatever other properties
}
然后在您的控制器中执行以下操作:
In your controller you'd then do:
[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
,以便它也可用于其他用户的视图.当然,您可以扩展视图模型以包含其他角色的功能属性(例如,管理员和版主可以访问的视图,每个视图都有各自独特的隐藏链接集),或为每个角色创建一个视图模型-所有这些都取决于场景.
I've named the viewmodel property ShowHiddenLinks
on purpose, so that it becomes re-usable for views meant for other users as well. You can of course extend the viewmodel to feature properties for other roles (e.g. a view which is accessible by admins and moderators, each with their own distinct set of hidden links), or create one viewmodel per role—it all depends on the scenario.
这篇关于ASP.Net MVC身份验证-根据角色在视图中隐藏元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!