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 »</a></p> }
How can I do this in Core 2.0?
Authorization in ASP.NET Core is controlled with AuthorizeAttribute and its various parameters. In its most basic form, applying the [Authorize] attribute to a controller, action, or Razor Page, limits access to that component to authenticated users. Now only authenticated users can access the Logout function.
One way to control access in your Razor Pages app is to use authorization conventions at startup. These conventions allow you to authorize users and allow anonymous users to access individual pages or folders of pages. The conventions described in this topic automatically apply authorization filters to control access.
isauthenticated is False when a user is already logged in.
Edit: David is right of course.
Just check if User
or HttpContext.User.Identity.IsAuthenticated
is true
or not.
@if(!User.Identity.IsAuthenticated) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With