是否有可能将Authorize-Attribute的结果交给View?
假设我想根据用户的成员身份在Index视图中隐藏5个链接。
[Authorize(Roles = "Admin")]
public ActionResult Index(){
....
}上面的代码将阻止不属于Admin-Group的所有用户访问Index页面。
@{
if(User.IsInRole("Admin"){
<a href="#">Some link to be hidden</a>
}
}如果用户不是Admin角色的一部分,此代码将隐藏链接。这基本上就是我想要的,但使用这种方法,如果角色发生变化,我必须更改每个隐藏链接上的角色名称。
是不是有一种类似两者的组合?(模式见下文)
[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>
}
}所以-如果用户是“管理员”的角色,该链接将显示。这个是可能的吗?
发布于 2016-10-20 02:02:53
您可以使用ViewBag和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>
}我特意将视图模型属性命名为ShowHiddenLinks,这样它就可以重用于其他用户的视图。当然,您可以扩展视图模型,使其具有其他角色的特性(例如,管理员和版主可以访问的视图,每个管理员和版主都有自己独特的隐藏链接集),或者为每个角色创建一个视图模型-这完全取决于场景。
https://stackoverflow.com/questions/40138070
复制相似问题