How to check if user is authenticated in Razor pages of .Net Core 2.0

asp.net MvcAuthenticationRazorasp.net Core

asp.net Mvc Problem Overview


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?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

Edit: David is right of course.

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

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

Solution 2 - asp.net Mvc

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoddy BalkanView Question on Stackoverflow
Solution 1 - asp.net MvcTsengView Answer on Stackoverflow
Solution 2 - asp.net Mvcvini bView Answer on Stackoverflow