c# - 使用授权属性验证登录用户的身份

标签 c# asp.net asp.net-mvc asp.net-identity

我正在创建一个新的 ASP.NET Web 应用程序,我不打算使用“角色”的概念。但是,我确实想确保用户在某些页面上登录。是否有任何现有属性可以简单地检查用户是否已登录并重定向他们或如果他们没有则抛出错误?我所做的每一次搜索都指向使用角色(例如 this one )。

最佳答案

[Authorize] 属性仅在发起请求的用户已登录时才会成功返回,并且仅适用于 Controller 和操作方法。

它可以用来装饰一个特定的 Action :

public class FooController : Controller
{
    // only FooAction requires authentication in FooController
    [Authorize]
    public async Task<ActionResult> FooAction()
    {        

    }

    public async Task<ActionResult> BarAction()
    {

    }
}

...或整个 Controller :

// all actions in FooController require authentication
[Authorize]
public class FooController : Controller
{
    public async Task<ActionResult> FooAction()
    {        

    }

    public async Task<ActionResult> BarAction()
    {

    }
}

您还有 Request.IsAuthenticated 可用于操作和非操作方法:

if (Request.IsAuthenticated) //or @if in Razor
{
    //request is authenticated 
}

...甚至 User.Identity.IsAuthenticated 正如@Darko 在他的回答中正确指出的那样。就个人而言,我更喜欢 Request.IsAuthenticated 而不是 User.Identity.IsAuthenticated 因为它还为 UserUser 提供了一些有用的空值检查.身份。以下是 Request.IsAuthenticated 的内幕:

public bool IsAuthenticated
{
    get
    {
        return(_context.User != null 
               && _context.User.Identity != null 
               && _context.User.Identity.IsAuthenticated);
    }
}

关于c# - 使用授权属性验证登录用户的身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32407322/

相关文章:

c# - Uncaught ReferenceError : __doPostBack is not defined

c# - 关键字 `ref` 如何影响内存管理和垃圾回收?

c# - VB.NET linq group by 匿名类型不能按预期工作

jquery - 如何使用 Web API 调用中的数据填充 jquery DataTable

asp.net-mvc - MVC 音频控制从字节播放歌曲

C# MVC ViewModel 返回 Null - 回传

c# - StoreGeneratedPattern 是什么意思?

javascript - 使用 JavaScript 的两个 Ajax 日期时间选择器之间的天数

c# - C# 中的 MPXJ 库示例

c# - asp.net如何将首页设置为默认页面