BootstrapAsp.Net MVC 5使用Identity之简单的登记与登陆

由于.Net MVC
5登陆和报方式发出好多种植,但是Identity方式去贯彻或许会再次简短又易于了解

率先新建一个种类

Bootstrap 1

 

下如下选择Empty和MVC的选项

Bootstrap 2

然后打开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

Bootstrap 3

然后向Models文件夹里面添加ApplicationUser类,SignInModel类,SignUpModel类,ApplicationDbContext类,当然ApplicationDbContext类你为堪划分至DbContext到另外一个类库,我这是召开示范用的,分层不用么这么肯定


ApplicationUser类

Bootstrap 4

ApplicationDbContext类

Bootstrap 5

SignInModel类

Bootstrap 6

SignUpModel类

Bootstrap 7

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


ApplicationUserManager类

Bootstrap 8

ApplicationSignInManager类

Bootstrap 9

ApplicationUserStore类

 

Bootstrap 10

下一场往Controller文件夹里面添加HomeController控制器,AccountController控制器

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

Bootstrap 11

Bootstrap 12

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>
}

Bootstrap 13

下一场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; }
        }

Bootstrap 14

下一场分别上加生成Login和Register页面

Bootstrap 15

Bootstrap 16

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>

Bootstrap 17

BootstrapRegister页面代码

@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>
}

Bootstrap 18

下一场为项目之绝望目录上加Startup类

Bootstrap 19

Bootstrap 20

接下来修改根目录的Web.Config文件

Bootstrap 21

末我们来测试一下瞧效果怎么样,如下图

Bootstrap 22

Bootstrap 23

Bootstrap 24

Bootstrap 25

相关文章