57

I would like to check if a user is logged in in an ASP.NET Core 2.0 application in a Razor page. The following code worked in .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>
}

How can I do this in Core 2.0?

Bryan
  • 2,870
  • 24
  • 39
  • 44
Roddy Balkan
  • 1,559
  • 4
  • 15
  • 22
  • Possible duplicate of [Check if user is logged in with Token Based Authentication in ASP.NET Core](https://stackoverflow.com/questions/41315903/check-if-user-is-logged-in-with-token-based-authentication-in-asp-net-core) – Vano Maisuradze Feb 22 '19 at 07:49

2 Answers2

128

Edit: David is right of course.

Just check if User or HttpContext.User.Identity.IsAuthenticated is true or not.

@if(!User.Identity.IsAuthenticated) 
{
    ...
}
Tseng
  • 61,549
  • 15
  • 193
  • 205
1

I've always used this option.

 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();
        }

Hope it helps someone!

vini b
  • 59
  • 10