zoukankan      html  css  js  c++  java
  • Identity用户管理入门七(扩展用户字段)

    在实际使用时会发现很多字段在IdentityUser中并不存在,比如增加生日,地址等字段,可在模型类中实现自己的模型并继承自IdentityUser,需要修改的代码为以下类

    一、新增模型

    using System;
    using Microsoft.AspNetCore.Identity;
    
    namespace Shop.Models
    {
        public class MyUser:IdentityUser
        {
            public string IdCard { get; set; }
            public DateTime Birthday { get; set; }
        }
    }

    二、修改Startup.cs

    修改前
    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();
    修改后
    services.AddDefaultIdentity<MyUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();

    三、修改ApplicationDbContext.cs

    using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore;
    
    namespace Shop.Models
    {
        public class ApplicationDbContext:IdentityDbContext<MyUser>
        {
            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
                : base(options)
            {
            }
            public DbSet<Region> Region { get; set; }
        }
    }

    四、更新扩展字段到数据库

    PM> Add-Migration addExtUser
    PM> Update-Database

    五、修改实现代码,以创建用户为例,红色字体为继承自IdentityUser的类库

    [HttpPost]
    public async Task<IActionResult> Register(CreateUserViewModel input)
    {
        if (ModelState.IsValid)
        {
            var user = new MyUser()
            {
                Id = input.id,
                UserName = input.UserName,
                Email = input.Email,
                PhoneNumber = input.PhoneNumber,
                Birthday = input.Birthday
    
            };
            //创建用户
            var result = await _userManager.CreateAsync(user,input.PasswordHash);
            //如果成功则返回用户列表
            if (result.Succeeded)
            {
                return RedirectToAction("Index");
            }
        }
        return View(input);
    }

    可看到Birthday已经可以使用,视图记得@model引用也修改下才能展示,如下代码

    @model IEnumerable<MyUser>
    @inject SignInManager<MyUser> SignInManager
  • 相关阅读:
    洛谷P2522 [HAOI2011]Problem b(莫比乌斯反演)
    洛谷P3327 [SDOI2015]约数个数和(莫比乌斯反演)
    Informatica PowerCenter 常用转换组件一览表
    Informatica_(3)组件
    Informatica_(2)第一个例子
    Informatica_(1)安装
    InformaticaPowerCenter调用存储过程
    Informatica 9.5.1 安装配置
    Linux字符集的查看及修改
    Redis-3.2.9集群配置(redis cluster)
  • 原文地址:https://www.cnblogs.com/liessay/p/13208941.html
Copyright © 2011-2022 走看看