扩展ASP.NET身份
从许多方面来看,这似乎已被多次询问,但这些似乎都不适合我的确切情况。
这是我的_LoginPartial.cshtml文件中的一行:
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
请参阅说明User.Identity.GetUserName()的部分?
我想将其更改为User.Identity.FirstName或User.Identity.GetFirstName()。
我不希望它说“你好电子邮件地址”,而是“Hello Bob”
我的想法是,我只是想在Identity类上显示一个新的属性(或方法)。 显然它必须不止于此。
我添加了FirstName属性, 它在AccountController中可用 。
public class ApplicationUser : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; }
它不会在_LoginPartial文件中公开。 我希望它暴露在那里!
谢谢您的帮助
即使你的答案不是“我想要的”,你的评论也让我得到了这个解决方案:
@using Microsoft.AspNet.Identity @using YourModelnameHere.Models @if (Request.IsAuthenticated) { using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" })) { @Html.AntiForgeryToken()
} }
在我的IdentityModel.cs文件中,我添加了两个属性FirstName和LastName
public class ApplicationUser : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } }
我通过在用户登录时向声明添加免费精选名字大全和姓氏,然后编写我自己的扩展方法来完成此操作。
当用户登录时,将所需的详细信息添加到声明集( AccountController
):
private async Task SignInAsync(ApplicationUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); // Add the users primary identity details to the set of claims. var pocoForName = GetNameFromSomeWhere(); identity.AddClaim(new Claim(ClaimTypes.GivenName, pocoForName)); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); }
扩展方法,它只是从用户的声明集中提取细节:
public static class IdentityExtensions { public static IdentityName GetGivenName(this IIdentity identity) { if (identity == null) return null; return (identity as ClaimsIdentity).FirstOrNull(ClaimTypes.GivenName); } internal static string FirstOrNull(this ClaimsIdentity identity, string claimType) { var val = identity.FindFirst(claimType); return val == null ? null : val.Value; } }
现在在partial中,只需调用新的扩展方法即可获得所需的详细信息:
@Html.ActionLink("Hello " + User.Identity.GetGivenName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
编辑:更新以更紧密地匹配SignInAsync()方法的原始海报版本
private async Task SignInAsync(ApplicationUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await user.GenerateUserIdentityAsync(UserManager); //add your claim here AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); }
为Asp .net Core更新了答案! 希望这可以节省一些时间给其他用户。
@if (SignInManager.IsSignedIn(User)){
}
上述就是C#学习教程:扩展ASP.NET身份分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1005309.html