当前位置: 移动技术网 > IT编程>开发语言>.net > Asp.net Mvc身份验证

Asp.net Mvc身份验证

2018年03月31日  | 移动技术网IT编程  | 我要评论

1、安装组件 Microsoft.AspNet.Identity.Core,身份认证核心组件

安装Microsoft.AspNet.Identity.EntityFramework,EF实现身份认证

安装Microsoft.AspNet.Identity.OWIN,身份认证的OWIN插件,用于替代Froms验证

安装Microsoft.Owin.Host.SystemWeb 3.1.0,可以让OWIN运行在IIS上

2、添加Identity EF 上下文,并配置好数据库连接字符串

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.Identity.EntityFramework;

namespace IdentityTest.Models
{
    public class AppIdentityDbContext : IdentityDbContext<IdentityUser>
    {
        public AppIdentityDbContext() : base("DefaultConnection") {

        }
    }
}

3、使用enable-migrations在程序包控制台进行开启迁移,使用update-database更新数据库,数据库生成了相应的五张表

4、添加注册功能,为了方便调式使用GET方法

 [HttpGet]
        public ActionResult Register(string UserName, string Password)
        {
            var user = new IdentityUser
            {
                UserName = UserName
            };
            using (var userManager = new UserManager<IdentityUser, string>
                (new UserStore<IdentityUser>(new AppIdentityDbContext())))
            {
                var result = userManager.Create(user, Password);
                if (result.Succeeded)
                {
                    return Json(new { IsSuc = true, Message = "注册成功" },JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(new { IsSuc = false, Message = result.Errors.ToString() },JsonRequestBehavior.AllowGet);
                }
            }

        }

启动运用程序发现报错,在appSettings里面添加

<add key="owin:AutomaticAppStartup" value="false" />

重新运行 在浏览器输入http://localhost:58009/Home/Register?UserName=admin&Password=123456 显示注册成功

查询数据库,[dbo].[AspNetUsers]表新增了一条刚才的注册用户

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网