且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查用户是否在 Action 中获得授权

更新时间:2023-11-29 16:39:52

如果只想知道用户是否登录:

If you just want to know if the user is logged in:

if (User.Identity.IsAuthenticated) { ... }

如果您正在尝试做任何特定于角色的事情:

If you are trying to do anything role-specific:

if (User.IsInRole("Administrators")) { ... }

User 实例是 Controller 类的公共属性,因此您始终可以从您编写的控制器访问它.如果没有用户登录,您应该为 User 设置一个 GenericPrincipal,为 User.Identity 设置一个 GenericIdentity,所以不用担心检查空值.

The User instance is a public property of the Controller class, so you always have access to it from a Controller you write. If no user is logged in you should have a GenericPrincipal for the User and a GenericIdentity for the User.Identity, so don't worry about checking for nulls.