Asp.Net MVC 5使用Identity之简单的注册和登陆

由于.Net MVC 5登陆和注册方式有很多种,但是Identity方式去实现或许会更简单更容易理解

首先新建一个项目

其次如下选择Empty和MVC的选项

然后打开NuGet包管理器分别安装几个包

  1. EntityFramework
  2. Microsoft.AspNet.Identity.Core
  3. Microsoft.AspNet.Identity.EntityFramework
  4. Microsoft.AspNet.Identity.Owin
  5. Modernizr
  6. Microsoft.Owin.Host.SystemWeb
  7. Bootstrap

然后往Models文件夹里面添加ApplicationUser类,SignInModel类,SignUpModel类,ApplicationDbContext类,当然ApplicationDbContext类你也可以分到DbContext到另一个类库,我这是做演示用的,分层不用么这么明确

----------------------------------------------------------------------

ApplicationUser类

ApplicationDbContext类

SignInModel类

SignUpModel类

然后往App_Start文件夹里面添加ApplicationSignInManager类,ApplicationUserManager类,ApplicationUserStore类

---------------------------------------------------------------------

ApplicationUserManager类

ApplicationSignInManager类

ApplicationUserStore类

然后往Controller文件夹里面添加HomeController控制器,AccountController控制器

先往HomeController控制器里添加index视图

index视图代码

@using Microsoft.AspNet.Identity
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@if (Request.IsAuthenticated)
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
        @Html.AntiForgeryToken()
        <p>Hello @User.Identity.GetUserName()</p>
        <ul>
            <li><a href="javascript:document.getElementById(‘logoutForm‘).submit()">Log off</a></li>
        </ul>
    }
}
else
{
    <ul>
        <li>
            @Html.ActionLink("Login", "Login", "Account")
        </li>
        <li>
            @Html.ActionLink("Register", "Register", "Account")
        </li>
    </ul>
}

然后AccountController控制器代码

private ApplicationSignInManager signInManager;
        private ApplicationUserManager userManager;

        public ApplicationSignInManager SignInManager
        {
            get
            {
                return signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
            }
            private set
            {
                signInManager = value;
            }
        }
        public ApplicationUserManager UserManager
        {
            get { return userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
            private set
            {
                userManager = value;
            }
        }

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(SignInModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "登陆无效");
                    return View(model);
            }

        }

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(SignUpModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }
            return View(model);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            AuthenticationManager.SignOut();
            return RedirectToAction("Index", "Home");
        }
        private void AddErrors(IdentityResult result)
        {
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }
        }
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            return RedirectToAction("Index", "Home");
        }
        private IAuthenticationManager AuthenticationManager
        {
            get { return HttpContext.GetOwinContext().Authentication; }
        }

然后分别添加生成Login和Register页面

Login页面代码

@model IdentityDemo.Models.SignInModel

@{
    ViewBag.Title = "Login";
}

<h2>Login</h2>

@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>SignInModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.PasswordFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.RememberMe, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.CheckBoxFor(model => model.RememberMe)
                    @Html.ValidationMessageFor(model => model.RememberMe, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="SignIn" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("注册", "Register")
</div>

Register页面代码

@model IdentityDemo.Models.SignUpModel

@{
    ViewBag.Title = "Register";
}

<h2>Register</h2>

@using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>SignUpModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })

            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.PasswordFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.PasswordFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })

            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="SignUp" class="btn btn-default" />
            </div>
        </div>
    </div>
}

然后往项目的根目录添加Startup类

然后修改根目录的Web.Config文件

最后我们来测试一下看看效果怎么样,如下图

时间: 2024-08-05 14:05:06

Asp.Net MVC 5使用Identity之简单的注册和登陆的相关文章

Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理

这是本人第一次写,写的不好的地方还忘包含.写这个的主要原因是翔通过这个来学习下EF的CodeFirst模式,本来也想用AngularJs来玩玩的,但是自己只会普通的绑定,对指令这些不是很熟悉,所以就基本不用了.还有最主要的原因就是锻炼下自己的能力.好了其他就不多说了,下面来看下我对这个项目的整体概述吧: 目录: 目录我以后会在这边添加上去的 一.Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理 基本设计 项目中使用到的工具: Visual Studio 2013,

Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理6

接下来先做角色这一板块的(增删改查),首先要新建一个Role控制器,在添加一个RoleList的视图.表格打算采用的是bootstrap的表格. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AuthorDesign.Web.Areas.Admin.Controllers { public class Role

Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理10

今天把用户的菜单显示和页面的按钮显示都做好了,下面先来个效果图 接下来说下我实现的方法: 首先我在每个方法前面都加了这个属性, /// <summary> /// 表示当前Action请求为一个具体的功能页面 /// </summary> public class AdminActionMethod : Attribute { /// <summary> /// 页面请求路径 /// </summary> public string ActionUrl {

Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理1

首先给上项目的整体框架图:,这里我没有使用BLL,因为感觉太烦了就没有去使用. 那么接下来我们首先先去Model层中添加Model. 管理员类: using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.

Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理7

做完角色之后接下来做先做页面按钮的增加.删除.修改.这里用到的功能和角色那边是一样的.就不多说了.直接上代码. 后台控制器代码 using AuthorDesign.Web.App_Start.Common; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AuthorDesign.Web.Areas.Admin

ASP.NET MVC - 多国语言的简单实现

定义一个类 public class Book{    public int ID { get; set; }    public string Title { get; set; }    public string Author { get; set; }    public double Price { get; set; }    public double Action { get; set; }} 右击项目-添加ASP.NET文件夹-创建App_GlobalResources-右击此

Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理2

首先我们来写个类进行获取当前线程内唯一的DbContext using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading.Tasks; namespace AuthorDesign.DAL { /// <sum

Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理9

前两天因有事就没来得及写.今天刚刚好空了.这次写的是对角色和管理员对页面按钮之间的控制.先看页面效果 说明:先根据角色设置好角色的权限,然后管理员在对应的角色下的权限去设置其权限. 在设置角色权限的时候 当某个角色对应某个页面的按钮都是未选中的时候,则设置它的IsShow为0,反之则为1,这样有利于设置管理员的时候方便查询需要设置的页面. 当isshow为0的时候删除管理员表对应的该页面Id的记录. 角色和管理员页面按钮显示这块到这里就结束了. 百度网盘源码下载地址

Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理3

首先在webconfig中加入下面这句代码,这个主要是用来生成数据库的连接字符串 <connectionStrings> <add name="AuthorDesignContext" providerName="System.Data.SqlClient" connectionString="Data Source=.;Initial Catalog=AuthorDesign;Integrated Security=False;User