您现在的位置是:网站首页> 编程资料编程资料
ASP.NET MVC使用Identity增删改查用户_实用技巧_
2023-05-24
304人已围观
简介 ASP.NET MVC使用Identity增删改查用户_实用技巧_
源码在这里:https://github.com/darrenji/UseIdentityCRUDUserInMVC,本地下载
在VS2013中创建一个MVC项目,用默认的"无身份验证"作为身份验证机制。
通过控制台下载Bootstrap。
Install-Package -version 3.0.3 bootstrap
下载成功后,在解决方案下的Content和Scripts多了该版本的css和js文件。
把创建项目默认HomeController中的所有Action以及/Views/Home下的所有视图删除。
热热身
先来做一个简单练习。
在HomeController中的Index方法中,把一个字典传递给视图。
public class HomeController : Controller { public ActionResult Index() { Dictionary data = new Dictionary(); data.Add("placeholder", "placeholder"); return View(data); } } _Layout.cshtml设置如下:
ASP.NET Identity实战 @RenderBody()@Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false)
Home/Index.cshtml视图中:
@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } 用户明细 @foreach (string key in Model.Keys) { @key @Model[key] }

前期准备
分别安装如下组件。
Install-Package Microsoft.AspNet.Identity.EntityFramework –Version 2.0.0
Install-Package Microsoft.AspNet.Identity.OWIN -Version 2.0.0
Install-Package Microsoft.Owin.Host.SystemWeb -Version 2.1.0
配置Web.config如下:
以上,
- 增加了connectionStrings节点,将自动创建localdb数据库
- 在appSettings节点中增加了一个key为owin:AppStartup项,这是确保OWIN运行正常的全局配置
在Models文件夹下创建如下类。
public class AppUser : IdentityUser { }在解决方案下创建Infrastructure文件夹。
在Infrastructure文件夹下创建一个上下文类,需要实现IdentityDbContext<>接口。
public class AppIdentityDbContext : IdentityDbContext{ public AppIdentityDbContext() : base("IdentityDb") { } static AppIdentityDbContext() { //使用EF Code First第一次创建的时候调用 Database.SetInitializer (new IdentityDbInit()); } public static AppIdentityDbContext Create() { return new AppIdentityDbContext(); } } //初始化 public class IdentityDbInit : DropCreateDatabaseIfModelChanges { protected override void Seed(AppIdentityDbContext context) { PerformInitialSetup(context); base.Seed(context); } //初始化工作 public void PerformInitialSetup(AppIdentityDbContext context) { } }
在Infrastructure文件夹下创建一个管理用户的类,需要继承UserManager
还记得,先前在appSettings节点中配置了一个如下方式:
OWIN需要一个全局启动文件,默认会到项目的顶级命名空间下找IdentityConfig这个类。
那就在App_Start中创建IdentityConfig这个类,这个类在WebApplication4这个命名空间下。
namespace WebApplication4 { public class IdentityConfig { public void Configuration(IAppBuilder app) { app.CreatePerOwinContext(AppIdentityDbContext.Create); app.CreatePerOwinContext(AppUserManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new Microsoft.Owin.PathString("/Account/Login") }); } } } 显示用户
创建AdminController,现在可以向视图传递所有的用户了,编写如下:
public class AdminController : Controller { public ActionResult Index() { return View(UserManager.Users); } private AppUserManager UserManager { get { return HttpContext.GetOwinContext().GetUserManager(); } } } 再创建Admin/Index.cshtml类型为IEnumerable
@model IEnumerable@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } @Html.ActionLink("创建用户", "Create", null, new { @class = "btn btn-primary" })所有用户账户
@if (Model.Count() == 0) { ID Name } else { foreach (WebApplication4.Models.AppUser user in Model) { 还没有创建用户 } } @user.Id @user.UserName @user.Email @using (Html.BeginForm("Delete", "Admin", new { id = user.Id })) { @Html.ActionLink("编辑", "Edit", new { id = user.Id }, new { @class = "btn btn-primary btn-xs" }) }

创建用户
在Models文件夹下创建一个视图模型。
namespace WebApplication4.Models { public class CreateModel { public string Id { get; set; } [Required] public string Name { get; set; } [Required] public string Email { get; set; } [Required] public string Password { get; set; } } }在AdminController中添加创建用户相关的方法。
public class AdminController : Controller { public ActionResult Index() { return View(UserManager.Users); } //创建显示 public ActionResult Create() { return View(); } [HttpPost] public async Task Create(CreateModel model) { if(ModelState.IsValid) { var user = new AppUser{UserName = model.Name, Email = model.Email}; IdentityResult result = await UserManager.CreateAsync(user, model.Password); if(result.Succeeded) { return RedirectToAction("Index"); }else{ AddErrorsFromResult(result); } } return View(model); } //创建接收 private void AddErrorsFromResult(IdentityResult result) { foreach(var error in result.Errors) { ModelState.AddModelError("", error); } } private AppUserManager UserManager { get { return HttpContext.GetOwinContext().GetUserManager(); } } } 在Admin/Create.cshtml视图页中:
@model WebApplication4.Models.CreateModel @{ ViewBag.Title = "Create"; Layout = "~/Views/Shared/_Layout.cshtml"; } Create
@using (Html.BeginForm()) { @Html.AntiForgeryToken() 创建用户
@Html.ValidationSummary(true) @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" }) @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) @Html.LabelFor(model => model.Email, new { @class = "control-label col-md-2" }) @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => mo
相关内容
- ASP.NET Identity的基本用法_实用技巧_
- ASP.NET MVC把数据库中枚举项的数字转换成文字_基础应用_
- ASP.NET MVC限制同一个IP地址单位时间间隔内的请求次数_实用技巧_
- .NET中lambda表达式合并问题及解决方法_实用技巧_
- asp.net core 中的Jwt(Json Web Token)的使用详解_实用技巧_
- 老生常谈.NET中的 COM 组件_实用技巧_
- .Net中Task Parallel Library的进阶用法_实用技巧_
- ASP.NET延迟调用或多次调用第三方Web API服务_实用技巧_
- 使用HttpClient消费ASP.NET Web API服务案例_实用技巧_
- 使用HttpClient增删改查ASP.NET Web API服务_实用技巧_
点击排行
本栏推荐
