.NET 自定义授权属性 (mvc)

发布于 2024-10-08 14:06:34 字数 252 浏览 3 评论 0原文

在某些控制器中我有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我爱人 2024-10-15 14:06:34

可以使用自定义 Authorize 属性来完成,但将逻辑放入控制器方法中会更清晰。

It can be done with a custom Authorize attribute, but it's much cleaner to put the logic inside your controller methods.

给不了的爱 2024-10-15 14:06:34

该属性与被调用的操作(控制器类方法)相关。在此基础上,与用户对正在操作的对象(来自您的模型)的所有权相关的任何属性实际上应该位于用户尝试操作的实体/类上。您可能会发现在模型方法中验证用户比使用属性来实现这一点更容易。

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.

北笙凉宸 2024-10-15 14:06:34

在我看来这是可能的,只需谷歌搜索“自定义授权属性”即可。

但也许最好用这样的方式查询数据库:

ContextOrSession.Query<Something>.Where(Something.Groups.Intersect(User.Groups).Count>0)

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:

ContextOrSession.Query<Something>.Where(Something.Groups.Intersect(User.Groups).Count>0)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文