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

编程入门 行业动态 更新时间:2024-10-11 01:10:24
本文介绍了如何检查用户是否在 Action 中获得授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

通常我使用 [Authorize] 保护我的操作,但这次我需要检查用户是否在操作中获得授权.

Usually I protect my Actions with [Authorize] but this time I need to check if a user is authorized inside the action.

例如

if(userIsAuthorized) { //do stuff } else { //return to login page }

我相信我正在使用表单身份验证"

I believe I am using 'Forms Authentication'

这个问题有点类似于 this 但给出的答案似乎都不起作用.

This question is kind of similar to this but none of the answers given seemed to work.

我已经做了更多的挖掘 - 似乎如果我在具有 [Authorize] 的 Action 上设置断点,User.Identity 已设置,但在没有它的 Actions 上,User.Identity为空,即使我已登录

I have done some more digging- it seems if I breakpoint on an Action that has [Authorize], the User.Identity is set, but on Actions without it, the User.Identity is empty, even if I am logged in

推荐答案

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

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.

更多推荐

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

本文发布于:2023-11-28 17:43:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643353.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:用户   Action

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!