检查用户是否在ASP.NET Core中登录

问题描述 投票:1回答:2

我是ASP.NET Core的新手,但我仍然很不舒服。无论如何,我想知道这种方法是否正确或是否存在更好的解决方案。

我正在检查每个页面上是否有用户登录。如果没有,我将页面重定向到登录页面:

public IActionResult Index()
{
    if (User.Identity.IsAuthenticated)
    {
        return View();
    }
    else
    {
        return Redirect("Identity/Account/Login");
    }
}

我将其添加到每个页面中。

c# asp.net-core
2个回答
0
投票

而不是添​​加User.Identity.IsAuthenticated(非常干燥),您应该签出DataAnnotations-[AllowAnonymous][Authorize]。您可以使用这些注释装饰整个控制器或特定方法,以允许对特定功能进行身份验证。

[AllowAnonymous]
public IActionResult Index()
{
    if (User.Identity.IsAuthenticated)
    {
        return View();
    }
    else
    {
        return Redirect("Identity/Account/Login");
    }
}

[Authorize]
public IActionResult OnlyAuthenticatedUsers()
{
  return View();
}

然后,如果用户未通过身份验证,则可以在Startup.cs中添加重定向规则。

查看此:


0
投票

使用授权动作过滤器

© www.soinside.com 2019 - 2024. All rights reserved.