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

前言

之前我们进行了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>

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>

然后在_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>

然后运行网站,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();
        }
    }
}

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

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

解决办法:

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

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

执行增加配置命令后

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

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

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

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

时间: 2024-08-29 17:41:00

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

【ASP.NET Core快速入门】(二)部署到IIS

原文:[ASP.NET Core快速入门](二)部署到IIS 配置IIS模块 ASP.NET Core Module载地址:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/aspnet-core-module?tabs=aspnetcore2x 安装后再IIS管理器模块页面会出现aspnetcoremodule 新建网站 修改应用池 网站发布 控制台方式 dotnet publish发布到项目文件的bin/deb

【ASP.NET Core快速入门】(一)环境安装

下载.NET Core SDK 下载地址:https://www.microsoft.com/net/download/windows https://www.microsoft.com/net/learn/get-started/windows 安装vs2017,安装的时候选择安装core跨平台 在控制台创建ASP.NET Core应用程序 在程序安装后,可以在控制台输入dotnet进行创建core应用程序 输入dotnet  --help查看命令帮助 .NET 命令行工具 (2.1.2) 使

ASP.NET Core快速入门(Jessetalk)(第2章:配置管理)

课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 任务9:配置介绍 命令行配置 Json文件配置 从配置文件文本到c#对象实例的映射 - Options 与 Bind 配置文件热更新 框架设计:Configuration 任务10:命令行配置 新建一个项目CommandLineSample--控制台应用(.NET Core) 依赖性右键--管理NuGet程序包--下载microsoft.aspnetcore.all 传入参数

ASP.NET Core快速入门(Jessetalk)(第三章:依赖注入)

课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 任务16:介绍 1.依赖注入概念详解 从UML和软件建模来理解 从单元测试来理解 2.ASP.NET Core 源码解析 任务17:从UML角度来理解依赖 1.什么是依赖 当一个类A完成某个任务需要另一个类B来帮助时,A就对B产生了依赖 例如CustomerController需要对customer进行新增或查找时用到EF,则对EF的Context产生了依赖 var cont

【ASP.NET Core快速入门】(十二)JWT 设计解析及定制

前言 上一节我们讲述的书如何使用jwt token,而且上一节的token是要加Authorization:bearer XXXXXXXXXXXX才能访问. 这一节我们来研究如何自定义类似jwt的token验证,也就是说直接从header中拿取我们想要的token 自己定制JWT 首先,继续在上一节的JwtAuthSample项目中的Startup.cs中的ConfigureServices方法中注释掉以下内容,然后自定义jwt token public void ConfigureServic

Asp.Net Core 快速入门-在Centos 上安装Nginx

第一步:添加CentOS 7EPEL 库 在终端运行一下命令 sudo yum install epel-release 第二步:安装Nginx 在终端运行命一下 sudo yum install nginx 你回答“yes”的提示后,nginx会完成安装到你的虚拟专用服务器(VPS) 第三步:启动Nginx sudo systemctl start nginx 启动完成之后我们就可以用CentOS的IP和80端口访问Nginx了 如果无法访问,说明还是有问题 If you are runnin

【ASP.NET Core快速入门】(三)准备CentOS和Nginx环境

基本软件 VMware虚拟机 centos:http://isoredirect.centos.org/centos/7/isos/x86_64/CentOS-7-x86_64-Minimal-1708.iso centos安装 打开VMware虚拟机,选择文件----新建虚拟机 一般下载好的CentOS系统放在VMware文件夹下 选择网络方式(一般NAT就够了) 后面的都选择默认的就行了 然后运行就可以了 语言选英文 选择位置 然后开始安装 输入密码root123 然后等待安装完成就可以了,

Asp.Net Core WebAPI入门整理(二)简单示例

一.Core WebAPI中的序列化 使用的是Newtonsoft.Json,自定义全局配置处理: // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //使用IMvcBuilder 配置Json序列化处理 services.AddMvc()

PyQt5快速入门(四)PyQt5高级窗口组件

PyQt5快速入门(四)PyQt5高级窗口组件 一.QTableView 1.QTableView简介 QTableView可以使用自定义的数据模型来显示内容,通过setModel绑定数据源,由QAbstractItemView类定义的接口来实现,使其能够显示由QAbstractItemModel类派生的模型提供的数据. 2.标准模型 QStringListModel 字符串链表数据模型QStandardItemModel标准数据项模型,存储任意结构层次的数据QDirModel 文件系统目录模型