我也不是很懂,看视频学习,有如问题请指正!
根据ASP.NET Core MVC 登录验证_哔哩哔哩_bilibili视频整理
ASP.NET Core 5.0
Entity Framework 5.0
作者使用的是MSSQL,我换成了MYSQL
首先创建项目,作者使用了ASP.NET Core Web App(MVC)模板
我创建的ASP.NET Core Web空模板
Microsoft.EntityFrameworkCore(5.0.9)
Microsoft.EntityFrameworkCore.Tools(5.0.9) 迁移相关操作需要的 实现Code First需要
Pomelo.EntityFrameworkCore.MySql(5.0.1) MySql 官方的都说不好使,我就用了这个社区的
user.cs
using System.ComponentModel.DataAnnotations; namespace EF1.Domain.Entities { public class User { public int Id { get; set; } [Display(Name = "用户名")] [MaxLength(20,ErrorMessage = "{0}长度不能大于{1}") ] public string Account { get; set; } public string Password { get; set; } } }View Code
MyDbContext.cs
using Microsoft.EntityFrameworkCore; using EF1.Domain.Entities; namespace EF1.Domain { public class MyDbContext:DbContext { public DbSet<User> Users { get; set; } public MyDbContext(DbContextOptions options):base(options) { } } }View Code
appsettings.json
{ "ConnectionStrings": { "Default": "host=localhost;port=3306;database=EFCore1;uid=root;pwd=root" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }View Code
Startup.cs
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using EF1.Domain; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; namespace EF1 { public class Startup { public IConfiguration Configuration { get; } //创建构造函数注入Configuration配置项 public Startup(IConfiguration configuration) { Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { //设置Mysql版本号信息,代码需要 var serverVersion = new MySqlServerVersion(new Version(5, 5, 23)); services.AddControllersWithViews();//根据自己需求配置是增加控制器和视图,还是只增加控制器AddControllers services.AddDbContext<MyDbContext>(options => { options.UseMySql(Configuration.GetConnectionString("Default"), serverVersion); });//注册MyDbContext服务 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/home/login"; });//权限验证配置 } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); //登陆验证 app.UseAuthentication(); //授权验证 app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); } } }View Code
对于需要授权的相关类或者方法增加[Authorize]验证属性访问这些类或者方法就会触发登陆验证
当类设置有[Authorize]验证属性的,如果想给个别方法取消验证可以给对应方法上增加[AllowAnonymous]属性则不验证该方法
using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using EF1.Domain; using EF1.Domain.Entities; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.EntityFrameworkCore; namespace EF1.Controllers { [Authorize] public class HomeController : Controller { private readonly MyDbContext _context; public HomeController(MyDbContext context) { _context = context; } public IActionResult Index() { return Json("Home/Index"+HttpContext.User.Identity.Name); } /// <summary> /// 登陆访问页 /// </summary> /// <param name="returnUrl"></param> /// <returns></returns> [AllowAnonymous] public IActionResult Login(string returnUrl) { ViewBag.returnUrl = returnUrl; return View(); } /// <summary> /// 登陆请求Post页面 /// </summary> /// <param name="user"></param> /// <returns></returns> [AllowAnonymous] [HttpPost] public async Task<IActionResult> Login(UserLoginRequest user) { if (ModelState.IsValid)//模型数据验证 { if (await _context.Users.AnyAsync(a => a.Account == user.Account && a.Password == user.Password))//登陆验证 { var claims = new List<Claim> { new Claim(ClaimTypes.Name, user.Account) };//需要记录存储的数据,格式我也不会,死记硬背吧.. var claimnsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignInAsync(new ClaimsPrincipal(claimnsIdentity),new AuthenticationProperties{IsPersistent = true}); } else { return RedirectToAction(nameof(Login)); } } else { return UnprocessableEntity(ModelState); } return Redirect(user.ReturnUrl??"/"); } /// <summary> /// 退出请求页面 /// </summary> /// <returns></returns> public async Task<IActionResult> LoginOut() { await HttpContext.SignOutAsync(); return RedirectToAction(nameof(Login)); } } public class UserLoginRequest:User { public string ReturnUrl { get; set; } } }View Code