首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MVC5我应该使用哪一个来创建新用户:在AccountController中注册还是在ApplicationUserController中创建用户?

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

Stack Overflow用户
提问于 2016-06-19 06:49:35
回答 2查看 169关注 0票数 0

我正在用标识( MVC5,EntityFramework)编写一个代码。我被提供了两种创建用户的方法:在AccountController中注册(实现标识为1.0时默认)或在ApplicationUser中创建(添加控制器时默认)

问题是我应该用哪一个?AccountController注册方法还是ApplicationUser创建方法(默认情况下添加控制器)?

默认标识为1.0提供的注册方式

AccountsViewModel.cs

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
    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(模型)

代码语言:javascript
复制
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; }

}

EN

回答 2

Stack Overflow用户

发布于 2016-06-19 08:16:04

这取决于您是否明智,如果您正在通过身份管理管理您的用户,您可以使用帐户控制器,如果您有自己的安全库来管理用户,很可能您可以在不同的controller.this上进行管理,这都取决于您对用户管理的功能

1]会话登录

代码语言:javascript
复制
Or 

2]基于cookie的登录

票数 1
EN

Stack Overflow用户

发布于 2016-06-19 11:08:25

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37904681

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档