I am migrating a web application over to the new asp.net core
model, and have hit a sudden snag with one of the views.
I cannot find the migrated equivalent to User
and User.IsSignedIn()
under the new model - when used in views, like this...
@using System.Security.Claims
@if (User.IsSignedIn())
{
}
I've tried importing the Microsoft.AspNetCore.Mvc.Razor
library, where I thought it would be held, but it doesn't seem to work that way.
In ASP.NET Framework, you'd do this by accessing HttpContext. Current. User and its properties (see below for an example), in . NET Core this is handled via dependency injection.
GenerateUserIdentityAsync(manager), getUserIdCallback: (id) => (id. GetUserId<int>()) ) } }); Then, you can access the claim (in a view or in a controller):
Looking at the migration docs I think this might do it:
@using System.Security.Principal
@if (User.Identity.IsAuthenticated)
{
...
}
Found here: http://aspnetmvc.readthedocs.org/projects/mvc/en/latest/migration/migratingauthmembership.html
The approach adopted by the ASP.NET team for RC2 is to use SignInManager.IsSignedIn
:
@using Microsoft.AspNetCore.Identity
@using Mvc.Server.Models
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@if (SignInManager.IsSignedIn(User)) {
<form asp-controller="Account" asp-action="LogOff" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log off</button>
</li>
</ul>
</form>
}
else {
<ul class="nav navbar-nav navbar-right">
<li><a asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
}
Actually, the earlier answers are not always correct, because it depends on what "signed in" means. In Core, the IPrincipal is a ClaimsPrincipal. While it has an Identity property, which is of the type ClaimsIdentity, it's simply the first object in the Identities property collection. This is largely for backwards compatibility for the old ASP.NET. In the new world, no one identity is necessarily authoritative over the others... they're all valid.
Each of those identities has an IsAuthenticated property. You could, for example, have an identity that simply is tracking an anonymous user with some claims attached to it, so whatever created the identity would likely have set IsAuthenticated to false. On the other hand, the plumbing for the Cookie auth sets it to true when you've called a sign in method, but again, it depends on which identity a particular part of your app is paying attention to.
Also, in the RTM version, there is no IsSignedIn.
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