.NET 自定义授权属性 (mvc)
在某些控制器中我有 CRUD 方法。为了访问这些方法,用户需要登录。这就是我为此控制器使用 [Authorize]
属性的原因。现在我需要额外的属性来检查用户想要查看/删除/更新的项目是否属于他。
是否可以并建议使用属性来执行此操作,或者您建议在每个方法中使用检查方法?如果您建议使用属性,您能给我提供一些链接/说明吗?
编辑:
当然,如果属性返回 false,我不想将用户重定向到登录页面,而是向他显示错误消息......
In certain Controller I have CRUD methods. In order to access these methods user needs to be logged in. This is why I used [Authorize]
attribute for this controller. Now I need additional attribute which would check if item that user wants to view/delete/update belongs to him.
Is it possible and recommended to do this with attribute or you would suggest using check methods inside each method? If you suggest using attribute, could you please provide me some links/instructions?
EDIT:
Ofcourse, if attribute returns false than I don't want to redirect user to login page but show him an error message...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以使用自定义 Authorize 属性来完成,但将逻辑放入控制器方法中会更清晰。
It can be done with a custom Authorize attribute, but it's much cleaner to put the logic inside your controller methods.
该属性与被调用的操作(控制器类方法)相关。在此基础上,与用户对正在操作的对象(来自您的模型)的所有权相关的任何属性实际上应该位于用户尝试操作的实体/类上。您可能会发现在模型方法中验证用户比使用属性来实现这一点更容易。
The attribute is related to the action being called (the controller class method). On that basis any attribute relating to the user's ownership of the object being manipulated (from your Model) should really be on the entity/class that the user is attempting to manipulate. You'll probably find it easier to validate the user within the Model method rather than using an attribute to achieve this.
在我看来这是可能的,只需谷歌搜索“自定义授权属性”即可。
但也许最好用这样的方式查询数据库:
In my opinion it is possible, just google for 'Custom Authorize Attribute'.
But maybe it is better to query your database with something like this: