[英]MVC6 CORE identity claims in razor view
我在擺弄身份,我肯定在掙扎-我已經搜索了很多,但沒有任何顯示。
我想添加身份聲明,然后將其發布到頁面上的視圖中。
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var authenticationType = "Basic";
var userIdentity = new ClaimsIdentity(await manager.GetClaimsAsync(this), authenticationType);
// Add custom user claims here
userIdentity.AddClaim(new Claim("FirstName", this.FirstName));
return userIdentity;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
在我的注冊用戶中,我將這些保存到用戶:
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
// "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
請注意,我檢查了我的數據庫,並存儲了FirstName和LastName!
然后,我擴展了身份(注意,我刪除了原始返回值,以檢查它是否確實返回null)
public static class IdentityExtension
{
public static string GetFirstName(this IIdentity identity)
{
var claim = ((ClaimsIdentity)identity).FindFirst("FirstName");
// Test for null to avoid issues during local testing
// return (claim != null) ? claim.Value : string.Empty;
return claim.ToString() ;
}
}
我現在認為我應該能夠從_Navigation.cshtml中的剃刀視圖訪問數據。
@if (Context.User.Identity.IsAuthenticated)
{
<div class="dropdown profile-element">
<a data-toggle="dropdown" class="dropdown-toggle" href="#">
<span class="clear">
<span class="block m-t-xs">
<strong class="font-bold">Hello @User.Identity.GetFirstName()</strong>
</span>
我也嘗試不使用擴展名直接執行此操作:
@{
if (Context.User.Identity.IsAuthenticated)
{
var FirstName = ((ClaimsIdentity)User.Identity).FindFirst("FirstName");
}
}
我顯然缺少一些東西。我可以正常訪問常規用戶名。 我搜索了很多東西,甚至找到了很多東西,但是很多都是不同的版本,所以我被卡住了。
如果您能幫助我,我將不勝感激!
謝謝。
請遵循此處: 定制索賠轉換
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.