MVC5我应该使用哪一个来创建新用户:在AccountController中注册或在ApplicationUserController中创建用户?

时间:2016-06-19 06:49:36

标签: c# asp.net-mvc entity-framework asp.net-identity

我用身份编码MVC5(EntityFramework)。我已经提供了2种创建用户的方法: 在AccountController中注册(实现Identity 1.0时默认)或在ApplicationUser中创建(添加控制器时为默认值)

问题是我应该使用哪一个? AccountController注册方法或ApplicationUser Create Method(添加控制器时默认)?

默认情况下提供的注册方式身份1.0

enter image description here

AccountsViewModel.cs

public class RegisterViewModel
{
    public int ID { get; set; }
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

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

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    public string FirstMidName { get; set; }

    public string LastName { get; set; }

    public string UserName { get; set; }
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime EnrollmentDate { get; set; }
    public int DepotID { get; set; }
    public IEnumerable<SelectListItem> DepotList { get; set; }
    public IEnumerable<SelectListItem> DepartmentList { get; set; }

    public int DepartmentID { get; set; }

}

AccountController.cs

public class AccountController : Controller
{

    private ApplicationDbContext db = new ApplicationDbContext();
    public AccountController()       
    {
    }

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    private ApplicationUserManager _userManager;
    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        RegisterViewModel model = new RegisterViewModel();
        ConfigureRegisterViewModel(model);
        ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName");
        ViewBag.DepotID = new SelectList(db.Depots, "DepotID", "DepotName");
        return View(model);
    }
    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {

        if (!ModelState.IsValid)
        {
            ConfigureRegisterViewModel(model);
            return View(model);
        }

        if (ModelState.IsValid)
        {

            var user = new ApplicationUser() {
                UserName = model.UserName,
                Email = model.Email,
                FirstMidName = model.FirstMidName,
                LastName = model.LastName,
                EnrollmentDate = model.EnrollmentDate,
                DepotID = model.DepotID,
                DepartmentID = model.DepartmentID
            };
            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, "Confirm your account", "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);
    }

    private void ConfigureRegisterViewModel(RegisterViewModel model)
    {
        IEnumerable<Department> departments = db.Departments.OrderBy(u => u.DepartmentName);
        model.DepotList = departments.Select(a => new SelectListItem
        {
            Value = a.DepartmentID.ToString(),
            Text = a.DepartmentName.ToString()
        });
        IEnumerable<Depot> depots = db.Depots.OrderBy(u => u.DepotName);
        model.DepotList = depots.Select(a => new SelectListItem
        {
            Value = a.DepotID.ToString(),
            Text = a.DepotName.ToString()
        });
    }

}

应用程序用户创建默认情况下添加控制器

ApplicationUserController.cs

    public class ApplicationUserController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
        // GET: ApplicationUser/Create
        public ActionResult Create()
        {
            ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName");
            ViewBag.DepotID = new SelectList(db.Depots, "DepotID", "DepotName");
            return View();
        }

        // POST: ApplicationUser/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,IsAdministrator,LastName,FirstMidName,EnrollmentDate,DepartmentID,DepotID,Email,EmailConfirmed,PasswordHash,SecurityStamp,PhoneNumber,PhoneNumberConfirmed,TwoFactorEnabled,LockoutEndDateUtc,LockoutEnabled,AccessFailedCount,UserName")] ApplicationUser applicationUser)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(applicationUser);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

   //         ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName", applicationUser.DepartmentID);
   //         ViewBag.DepotID = new SelectList(db.Depots, "DepotID", "DepotName", applicationUser.DepotID);
            return View(applicationUser);
        }

    }

ApplicationUser.cs(型号)

public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
    public async Task<ClaimsIdentity>
        GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
    {
        var userIdentity = await manager
            .CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }

    public bool IsAdministrator { get; set; }
    [StringLength(50, MinimumLength = 1)]

    public string LastName { get; set; }
    [StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")]

    [Column("FirstName")]
    public string FirstMidName { get; set; }

    public string FullName
    {
        get { return FirstMidName + " " + LastName; }
    }
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime EnrollmentDate { get; set; }
    public int DepartmentID { get; set; }
    [ForeignKey("DepartmentID")]
    public virtual Department Department { get; set; }
    public int DepotID { get; set; }
    [ForeignKey("DepotID")]
    public virtual Depot Depot { get; set; }
    public virtual ICollection<Ticket> Tickets { get; set; }

}

enter image description here

2 个答案:

答案 0 :(得分:1)

这取决于你明智,如果你通过身份管理管理你的用户你可以使用帐户控制器,如果你有自己的安全库来管理用户,你很可能在不同的控制器上做这个。这一切都取决于您的用户管理功能,如

1]会话登录

Dim sName As String
Dim sSearchType As String
Dim sQry As String 

sName = TextBox1.Text
sSearchType = ComboBox1.Value

sQry = "SELECT * FROM ListBoxData "
Select Case sSearchType
    Case "All"
        'do nothing; return all records
    Case "StartsWith"
        sQry = sQry & "WHERE Name Like '" & sName & "*'"
    Case "Contains"
        sQry = sQry & "WHERE Name Like '*" & sName & "*'"
    Case "EndWith"
        sQry = sQry & "WHERE Name Like '*" & sName & "'"
End Select

Set rs = db.OpenRecordset(sQry)
'other stuff

2]基于cookie的登录

答案 1 :(得分:0)

不要按原样使用CRUD版本,或者根本不使用 - 自助服务允许人们使用注册方法,并在需要执行额外操作时扩展控制器后面的功能工作或设置更多属性。 自动脚手架版本基本上是一个开始,旨在用于新的视图模型,而不是像身份用户这样的框架类;通过公开该方法,任何人都可以创建自己的新管理员帐户,即使您从视图中删除了要设置此字段的字段。您应该遵循注释中的指导并删除对您不希望允许用户(或黑客)直接设置的任何属性的绑定,您还应该在控制器操作中实现访问控制。至少创建一个新的视图模型类来表示你的视图数据,而不是使用身份模型 - 然后嘿,你的控制器,视图和模型将更接近帐户控制器实现......