我正在创建一个新的 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
因为它还为 User
和 User 提供了一些有用的空值检查.身份
。以下是 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/