Mil*_*vic 10 c# asp.net-mvc asp.net-mvc-5 asp.net-identity-2
我正在使用带有身份2.1.0和VS2013 U4的ASP.NET MVC 5项目.我想在注册期间向用户添加声明,以便存储在db中.这些声明代表用户自定义属性.
当我为管理员创建一个用于创建/编辑/删除用户的网页时,我仍然使用create method AccountController来创建用户,但我不想登录该用户.如何将这些声明添加到用户?
pys*_*o68 13
你可能已经有了一UserManager堂课.您可以使用该用户创建用户并添加声明.
作为控制器中的示例:
// gather some context stuff
var context = this.Request.GetContext();
// gather the user manager
var usermanager = context.Get<ApplicationUserManager>();
// add a country claim (given you have the userId)
usermanager.AddClaim("userid", new Claim(ClaimTypes.Country, "Germany"));
Run Code Online (Sandbox Code Playgroud)
为了使其工作,您需要实现自己的UserManager并将其与OWIN上下文链接(在示例中,ApplicationUserManager它基本上class ApplicationUserManager : UserManager<ApplicationUser> { }只添加了少量配置).这里有一些阅读:https://msdn.microsoft.com/en-us/library/dn613290%28v=vs.108%29.aspx
小智 6
你可以使用Like
private void SignInAsync(User User)
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, User.Employee.Name));
claims.Add(new Claim(ClaimTypes.Email, User.Employee.EmailId));
claims.Add(new Claim(ClaimTypes.Role, User.RoleId.ToString()));
var id = new ClaimsIdentity(claims,
DefaultAuthenticationTypes.ApplicationCookie);
var claimsPrincipal = new ClaimsPrincipal(id);
// Set current principal
Thread.CurrentPrincipal = claimsPrincipal;
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(id);
}
Run Code Online (Sandbox Code Playgroud)
登录后,在此函数中传递User表值
SignInAsync(result);
Run Code Online (Sandbox Code Playgroud)
你可以得到蛤蜊价值
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
// Get the claims values
string UserRoleValue = identity.Claims.Where(c => c.Type == ClaimTypes.Role)
.Select(c => c.Value).SingleOrDefault();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17748 次 |
| 最近记录: |