【发布时间】:2017-03-24 19:10:42
【问题描述】:
我正在使用 asp.net Identity 2.0 让用户登录我的网站,其中身份验证详细信息存储在 SQL 数据库中。 Asp.net Identity 已以标准方式实现,可在许多在线教程中找到。
IdentityModels 中的 ApplicationUser 类已扩展为包含自定义属性:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
{
CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
return userIdentity;
}
//My extended property
public string Code { get; set; }
}
当我注册一个新用户时,我在 RegisterBindingModel 中传递了 Code 自定义属性,但我不确定如何将此自定义属性插入到 WebUsers 表中。
我做了如下操作,但实际上并没有将此属性连同用户名和密码一起插入到表中。
var user = new ApplicationUser() { UserName = userName, Email = model.Email, Code=model.Code };
以及整个函数:
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var userName = !string.IsNullOrEmpty(model.UserName) ? model.UserName : model.Email;
//I set it here but it doesn't get inserted to the table.
var user = new ApplicationUser() { UserName = userName, Email = model.Email, Code=model.Code };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
我错过了什么? 我正在查看类似的问题,但找不到答案。
【问题讨论】:
-
我觉得你的代码没问题,你确定
Code属性是在model参数里面填的吗? -
是的,我确定,我检查过了。但是当我检查数据库中的表时,新用户出现了,但代码字段始终是
null。 -
UserManager是如何定义的?看看github.com/tjoudeh/AspNetIdentity.WebApi
-
可能您确定您已按照所有步骤正确地向用户添加属性,无论如何我都与描述共享了所有步骤。试试看,我按照以下步骤成功添加了
Code字段↓
标签: c# .net asp.net-mvc asp.net-web-api asp.net-identity