码迷,mamicode.com
首页 > Web开发 > 详细

【ASP.NET Core快速入门】(十四)MVC开发:UI、 EF + Identity实现

时间:2018-01-05 18:02:01      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:解决   配置文件   login   method   def   targe   nas   dia   前言   

前言

之前我们进行了MVC的web页面的Cookie-based认证实现,接下来的开发我们要基于之前的MvcCookieAuthSample项目做修改。

MvcCookieAuthSample项目地址:http://www.cnblogs.com/wyt007/p/8128186.html

UI

我们首先在AccountController中添加两个Action

        public IActionResult SignIn()
        {
            return View();
        }

        public IActionResult Login()
        {
            return View();
        }

然后在Views文件夹下新增Account文件夹并新增Register.cshtml与Login.cshtml视图,样式我们尽量从上一节的Identity视图中拷贝过来。

我们还需要新建一个ViewModels,在ViewModels中新建RegisterViewModel.cs来接收表单提交的值以及来进行强类型视图

namespace MvcCookieAuthSample.ViewModels
{
    public class RegisterViewModel
    {
        //邮箱
        public string Email { get; set; }
        //密码
        public string Password { get; set; }
        //确认密码
        public string ConfirmedPassword { get; set; }
    }
}

Register.cshtml代码(只保留部分拷贝过来的内容,并加入强类型视图引用):

技术分享图片
@{
    ViewData["Title"] = "Register";
}

@using MvcCookieAuthSample.ViewModels;
@model RegisterViewModel;

<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

<div class="row">
    <div class="col-md-4">
        <form  method="post">
            <h4>Create a new account.</h4>
            <hr />
            <div class="form-group">
                <label asp-for="Email"></label>
                <input asp-for="Email" class="form-control" />
            </div>
            <div class="form-group">
                <label asp-for="Password"></label>
                <input asp-for="Password" class="form-control" />
            </div>
            <div class="form-group">
                <label asp-for="ConfirmedPassword"></label>
                <input asp-for="ConfirmedPassword" class="form-control" />
            </div>
            <button type="submit" class="btn btn-default">Register</button>
        </form>
    </div>
</div>
View Code

 

Login.cshtml代码(只保留部分拷贝过来的内容,并加入强类型视图引用):

技术分享图片
@{
    ViewData["Title"] = "Login";
}

@using MvcCookieAuthSample.ViewModels;
@model RegisterViewModel;

<div class="row">
    <div class="col-md-4">
        <section>
            <form  method="post">
                <h4>Use a local account to log in.</h4>
                <hr />

                <div class="form-group">
                    <label asp-for="Email"></label>
                    <input asp-for="Email" class="form-control" />
                </div>

                <div class="form-group">
                    <label asp-for="Password"></label>
                    <input asp-for="Password" type="password" class="form-control" />
                </div>

                <div class="form-group">
                    <button type="submit" class="btn btn-default">Log in</button>
                </div>

            </form>
        </section>
    </div>
</div>
View Code

 

然后在_Layout.cshtml中添加导航代码:

技术分享图片
<ul class="nav navbar-nav navbar-right">
    <li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
    <li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
View Code

然后运行网站,UI已经实现

 

技术分享图片

EF + Identity实现

EF实现

首先我们添加一个Data文件夹,由于VSCode的代码提示不是很好,接下来我们用VS2017开发。

我们首先在Models文件夹下面新建ApplicationUser.cs与ApplicationUserRole.cs

ApplicationUser.cs代码:

using Microsoft.AspNetCore.Identity;

namespace MvcCookieAuthSample.Models
{
    public class ApplicationUser:IdentityUser<int>//不加int的话是默认主键为guid
    {
    }
}

ApplicationUserRole.cs代码:

using Microsoft.AspNetCore.Identity;

namespace MvcCookieAuthSample.Models
{
    public class ApplicationUserRole: IdentityRole<int>//不加int的话是默认主键为guid
    {
    }
}

然后在Data文件夹下新建一个ApplicationDbContext.cs类,使它继承IdentityDbContext

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using MvcCookieAuthSample.Models;

namespace MvcCookieAuthSample.Data
{
    public class ApplicationDbContext:IdentityDbContext<ApplicationUser, ApplicationUserRole,int>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
        {

        }
    }
}

然后我们需要在Startup.cs添加EF的注册进来

//使用配置ApplicationDbContext使用sqlserver数据库,并配置数据库连接字符串
services.AddDbContext<ApplicationDbContext>(options=> {
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});

然后我们需要在appsettings.json中配置数据库连接字符串

"ConnectionStrings": {
  "DefaultConnection": "Server=192.168.1.184;Database=aspnet-IdentitySample-9A22BB3E-8D53-4F44-B533-2EF927C959DE;Trusted_Connection=True;MultipleActiveResultSets=true;uid=sa;pwd=123456"
}

EF实现结束

Identity实现

我们需要在Startup.cs添加Identity的注册进来

//配置Identity
services.AddIdentity<ApplicationUser, ApplicationUserRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

由于默认的Identity在密码上限制比较严格,我们把它改的宽松简单一点(不设置也行)

//修改Identity配置
services.Configure<IdentityOptions>(options =>
{
    options.Password.RequireLowercase = false;//需要小写
    options.Password.RequireNonAlphanumeric = false;//需要字母
    options.Password.RequireUppercase = false;//需要大写
});

然后我们把认证的地址改成/Account/Login

技术分享图片

然后我们修改AccountController,加入以下代码

private UserManager<ApplicationUser> _userManager;//创建用户的
private SignInManager<ApplicationUser> _signInManager;//用来登录的

//依赖注入
public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
    _userManager = userManager;
    _signInManager = signInManager;
}


[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel registerViewModel)
{
    var identityUser = new ApplicationUser
    {
        Email = registerViewModel.Email,
        UserName = registerViewModel.Email,
        NormalizedUserName = registerViewModel.Email
    };
    var identityResult=await _userManager.CreateAsync(identityUser, registerViewModel.Password);
    if (identityResult.Succeeded)
    {
        return RedirectToAction("Index", "Home");
    }

    return View();
}

 

完整的AccountController

技术分享图片
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MvcCookieAuthSample.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims;
using MvcCookieAuthSample.ViewModels;
using Microsoft.AspNetCore.Identity;

namespace MvcCookieAuthSample.Controllers
{

    public class AccountController : Controller
    {
        private UserManager<ApplicationUser> _userManager;//创建用户的
        private SignInManager<ApplicationUser> _signInManager;//用来登录的

        //依赖注入
        public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }


        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Register(RegisterViewModel registerViewModel)
        {
            var identityUser = new ApplicationUser
            {
                Email = registerViewModel.Email,
                UserName = registerViewModel.Email,
                NormalizedUserName = registerViewModel.Email
            };
            var identityResult=await _userManager.CreateAsync(identityUser, registerViewModel.Password);
            if (identityResult.Succeeded)
            {
                return RedirectToAction("Index", "Home");
            }

            return View();
        }

        public IActionResult Login()
        {
            return View();
        }



        //登陆
        public IActionResult MakeLogin()
        {
            var claims=new List<Claim>(){
                new Claim(ClaimTypes.Name,"wyt"),
                new Claim(ClaimTypes.Role,"admin")
            };

            var claimIdentity= new ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme);

            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(claimIdentity));

            return Ok();
        }

        //登出
        public IActionResult Logout()
        {
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            return Ok();
        }
    }
}
View Code

 

接下来我们重新生成一下,我们需要执行shell命令生成一下数据库,只有添加  Microsoft.EntityFrameworkCore.Tools  才会生成成功,否则会报以下错误

技术分享图片

执行命令总是提示 未找到与命令“dotnet-ef”匹配的可执行文件,根据网上的解决办法引用 Microsoft.EntityFrameworkCore.Tools 问题依旧不能得到解决。

解决办法:

右击项目弹出菜单点击编辑***.csprog,增加如下配置。

<ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>

执行增加配置命令后

技术分享图片

这时候Data文件夹下已经有新增的数据库更新配置文件了

技术分享图片

然后我们执行更新命令,执行成功后我们就可以看到数据库表已经生成了

技术分享图片

接下来我们运行一下网站进行注册,注册成功,已经存储进数据库

技术分享图片

 

【ASP.NET Core快速入门】(十四)MVC开发:UI、 EF + Identity实现

标签:解决   配置文件   login   method   def   targe   nas   dia   前言   

原文地址:https://www.cnblogs.com/wyt007/p/8204731.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!