如何避免授权码逻辑重复
我编写了一个派生自 System.Web 的自定义授权属性.Mvc.AuthorizeAttribute。我成功地从我的控制器中使用它来限制对某些功能的访问。
public class ArticleController : Controller
{
[CustomAuthorize(Role.Administrator)]
public ActionResult Delete(int id)
{
// ...
}
}
效果很好。现在我想根据相同的授权逻辑显示或隐藏 HTML 元素。例如,在我的视图“文章”中,如果用户不是管理员,我想隐藏操作按钮“删除”。我写过类似的东西:
<ul id="menu">
<li>@if (User.IsInRole(Role.Administrator)) {
@Html.ActionLink("Delete", "Delete", "Article", new { id = article.ID }, null)
} </li>
</ul>
它也工作得很好,但它会产生代码逻辑重复,因为我需要指定两倍的必要凭据来执行操作:
- 在控制器中阻止或允许该操作。
- 在视图中显示或隐藏操作链接。
避免这种重复的最佳方法是什么?有什么方法可以重用视图中的自定义授权属性吗?
I've written a custom authorization attribute derived from System.Web.Mvc.AuthorizeAttribute. I'm using it successfully from my controllers to restrict the access to certain features.
public class ArticleController : Controller
{
[CustomAuthorize(Role.Administrator)]
public ActionResult Delete(int id)
{
// ...
}
}
And that works fine. Now I want to show or hide HTML elements according to the same authorization logic. For example, in my view "Article", I want to hide the action button "Delete" if the user is not a administrator. I've written something like that:
<ul id="menu">
<li>@if (User.IsInRole(Role.Administrator)) {
@Html.ActionLink("Delete", "Delete", "Article", new { id = article.ID }, null)
} </li>
</ul>
It works fine as well, but it creates code logic duplication because I need to specify twice the necessary credientials to perform an action:
- In the controller to block or allow the action.
- In the view to show or hide the action link.
What is the best way to avoid this duplication? Is there any way to reuse my custom authorization attribute from views?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
自定义帮助程序应该是最好的选择,例如:
此帮助程序将检查某种服务以查看当前用户/角色是否具有此链接的权限。
A custom helper should be the best option, something like:
This helper would check on some kind of service to see if the current user/role has permission on this link.
使菜单成为局部视图。
Make the menu a partial view .
我会为此创建自定义 html 帮助器。
如果您觉得 Role 参数是多余的,您可以使用 Reflection 检查控制器操作并自动确定允许的角色。
I would create custom html helper for this.
And if you feel the Role parameter is redundant, you may inspect the controller action using Reflection and determine allowed roles automatically.