【问题标题】:How to check if user is authenticated in Razor pages of .Net Core 2.0如何检查用户是否在 .Net Core 2.0 的 Razor 页面中经过身份验证
【发布时间】:2018-02-03 21:50:10
【问题描述】:

我想检查用户是否在 Razor 页面中登录了 ASP.NET Core 2.0 应用程序。以下代码在 .NET 4.6.1 中工作:

@if (!Request.IsAuthenticated)
{
    <p><a href="@Url.Action("Login", "Account")" class="btn btn1-success btn-lg" role="button" area="">Sign In &raquo;</a></p>
}

如何在 Core 2.0 中做到这一点?

【问题讨论】:

标签: asp.net-mvc authentication razor asp.net-core


【解决方案1】:

编辑:大卫当然是对的。

只需检查UserHttpContext.User.Identity.IsAuthenticated 是否为true

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

【讨论】:

  • 这是不正确的。即使您未通过身份验证,用户也不为空。
  • 我只是将我的更改为@if (User.Identity.IsAuthenticated) { ... },它按预期工作
  • 适用于 asp.Net Core 2.0 ~ @if (User.Identity.IsAuthenticated) {} ~
【解决方案2】:

我一直使用这个选项。

 private readonly SignInManager<IdentityUser> _signInManager;

        public HomeController(SignInManager<IdentityUser> signInManager)
        {
            _signInManager = signInManager;
        }

        public IActionResult Index()
        {
            if (_signInManager.IsSignedIn(User)) //verify if it's logged
            {
                return LocalRedirect("~/Page");
            }
            return View();
        }

希望对某人有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    相关资源
    最近更新 更多