0

我在Visual Studio 2013上使用了asp.net Identity 2.0的Web項目。我按照此page上的說明創建了一個自定義新字段,我調用了screenName。一切似乎都很好。如何在ASP.NET身份中創建自定義配置文件信息UNIQUE

但是我想更進一步,並在數據庫中具有唯一的screenName。這意味着ApplicationUserManager必須在註冊用戶之前檢查是否獲取了屏幕名稱。我如何需要一個獨特的screenName並完成?

這裏是我的代碼:

AccountControler.cs(添加屏幕名= model.screenName)

public async Task<ActionResult> Register(RegisterViewModel model) 
    { 
     if (ModelState.IsValid) 
     { 
      var user = new ApplicationUser { UserName = model.Email, Email = model.Email, screenName = model.screenName }; 

      var result = await UserManager.CreateAsync(user, model.Password); 
      if (result.Succeeded) 
      { 
       var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); 
       var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); 
       await UserManager.SendEmailAsync(user.Id, "bla bla bla", "Thank you for your bla bla bla registration. Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>"); 
       ViewBag.Link = callbackUrl; 
       return View("DisplayEmail"); 
      } 
      AddErrors(result); 
     } 

     // If we got this far, something failed, redisplay form 
     return View(model); 
    } 

AccountViewModel.cs

public class RegisterViewModel 
{ 
[Required] 
[StringLength(20, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 
    [Display(Name = "screenName")] 
    public string screenName { get; set; } 
} 

IdentityModel.cs(加入公共字符串屏幕名{ get; set;})

public class ApplicationUser : IdentityUser 
{ 
    public string screenName { get; set; } 
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
    { 
     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
     // Add custom user claims here 

     return userIdentity; 
    } 
} 

Register.cshtml

<div class="form-group"> 
@Html.LabelFor(m => m.screenName, new { @class = "col-md-2 control-label" }) 
<div class="col-md-10"> @Html.TextBoxFor(m => m.screenName, new { @class = "form-control" }) 
</div> 
</div> 

SQL SERVER

GO 
CREATE UNIQUE NONCLUSTERED INDEX [screenNameIndex] 
ON [dbo].[AspNetUsers]([screenName] ASC); 

的ApplicationUserManager是,例如,需要具有對identityConfig.cs以下代碼的唯一電子郵件。我如何爲自定義screenName做同樣的事情?

var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>())); 
// Configure validation logic for usernames 
manager.UserValidator = new UserValidator<ApplicationUser>(manager) 
     { 
      AllowOnlyAlphanumericUserNames = false, 
      RequireUniqueEmail = true 
     }; 

回答

0

你需要手動檢查是否有與這個網名的記錄存在於DB:

事情是這樣的:

public async Task<ActionResult> Register(RegisterViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     // somehow obtain your DbContext object 
     var existsDuplicate = dbContext.Users.Any(u => u.screenName == model.screenName); 
     if(existsDuplicate) 
     { 
      ModelState.AddModelError("screenName", "Screen Name is already taken, please choose another one"); 
      return View(model); 
     } 


     // the rest of controller is unchanged 
     var user = new ApplicationUser { UserName = model.Email, Email = model.Email, screenName = model.screenName }; 

     var result = await UserManager.CreateAsync(user, model.Password); 
     if (result.Succeeded) 
     { 
      var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); 
      var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); 
      await UserManager.SendEmailAsync(user.Id, "bla bla bla", "Thank you for your bla bla bla registration. Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>"); 
      ViewBag.Link = callbackUrl; 
      return View("DisplayEmail"); 
     } 
     AddErrors(result); 
    } 

    // If we got this far, something failed, redisplay form 
    return View(model); 
} 
+0

謝謝你的答案。我試圖實現你的代碼,但出於某種原因,雖然我已經安裝了EntityFramework 6.1.1,但無法找到dbContext。我正在使用MVC5。我錯過了一個命名空間嗎? – Gloria 2014-09-03 10:23:31

+0

好的,我通過添加System.Data.Entity來解決問題。但是現在我得到另一個錯誤信息; 'System.Data.Entity.DbContext'不包含'Users'的定義...... – Gloria 2014-09-03 10:40:18

+0

您需要使用自己的數據庫上下文,這是從IdentityDbContext繼承的。上面的代碼是示例,不要從字面上理解。 – trailmax 2014-09-03 10:44:45

相關問題