參考網址
1.
https://www.dotblogs.com.tw/brooke/2014/08/01/146135
2. 這個才是重點
http://stackoverflow.com/questions/27683169/identity-2-0-creating-custom-claimsidentity-eg-user-identity-getuserbyidint
首先要先去擴充自己AspNetUsers的欄位,這就不多說明,像我現在就去
增加了兩個EmployeeId和Name。
接著這是我最原始的取得這兩個寫法
public static class AuthorizeExtensions
{
public static string GetEmployeeName(this IIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
var ci = identity as ClaimsIdentity;
if (ci != null)
{
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = UserManager.FindById(ci.GetUserId());
return user.EmployeeName;
}
return null;
}
}
但是一直到後來參考了這篇文章
http://stackoverflow.com/questions/27683169/identity-2-0-creating-custom-claimsidentity-eg-user-identity-getuserbyidint
首先,我先去到我登入的地方 改寫了登入方式
public ApplicationUser m_user = new ApplicationUser();
public async Task<ActionResult> Index(LoginViewModels LoginVM, string ReturnUrl)
{
m_user.Id = "帳號GUId";
m_user.UserName = "UserName";
//舊寫法,取不到EmployeeId,必須連接db再去找
//await SignInManager.SignInAsync(m_user, isPersistent: false, rememberBrowser: false);
//新寫法
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(m_user, DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim("EmployeeId", "編號"));
identity.AddClaim(new Claim("EmployeeName", "性明"));
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);
}
寫完之後,回到擴充方法那邊去改寫,只剩下一行
public static class AuthorizeExtensions
{
public static string GetEmployeeName(this IIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
return ((ClaimsIdentity)identity).FindFirstValue("EmployeeName");
}
}
這樣子就可以完全做到了,有什麼不對還請糾正指導