概述
Commond-Line
ASP.NET结构文件
Startup
配置文件
中间件和依赖注入
依赖注入原理
框架自带的依赖注入(IServiceCollection)
依赖注入生命周期
依赖注入使用方式
- 通过构造函数
- MVC的ActionAction中可以使用 [FromServices]来注入对象、
中间件(MiddleWare)
Use:进入中间件http管道模式,
Map:映射分支 Run:
执行,并返回Response
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMyMiddleware(); } public class MyMiddleware { private readonly RequestDelegate _next; public MyMiddleware(RequestDelegate next) { _next = next; } public Task Invoke(HttpContext context) { //这里是获取context信息后处理的代码 return this._next(context); } } public static class MyMiddlewareExtensions { public static IApplicationBuilder UseMyMiddleware( this IApplicationBuilder builder) { return builder.UseMiddleware<MyMiddlewareMiddleware>(); } }
中间件的执行要注意顺序,因为可以终止http管道的执行
框架自带中间件
ORM
Entity Framework Core
官方地址:https://docs.microsoft.com/zh-cn/ef/core/
services.AddDbContext<SchoolContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Entity Framework Core-Code First
//程序包管理控件台 Install-Package Microsoft.EntityFrameworkCore.SqlServer Install-Package Microsoft.EntityFrameworkCore.Tools Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design
从数据库生成模型
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
并发控制
//特性方式 public class Person { public int PersonId { get; set; } [ConcurrencyCheck] public string LastName { get; set; } public string FirstName { get; set; } } //特性API方式 class MyContext : DbContext { public DbSet<Person> People { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Person>() .Property(p => p.LastName) .IsConcurrencyToken(); } } public class Person { public int PersonId { get; set; } public string LastName { get; set; } public string FirstName { get; set; } } //特性时间戳 public class Blog { public int BlogId { get; set; } public string Url { get; set; } [Timestamp] public byte[] Timestamp { get; set; } }
//时间戳 class MyContext : DbContext { public DbSet<Blog> Blogs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(p => p.Timestamp) .IsRowVersion(); } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public byte[] Timestamp { get; set; } }
Dapper
官方地址:https://github.com/StackExchange/Dapper
权限验证
概念
Authentication:认证,通过自定义或三方的方式,确定用户有效性,并分配用户一定身份
Authorization:授权,决定用户可以做什么,可以带上角色或策略来授权,并且是能过Controller或Action上的特性Authorize来授权的。
验证方式
ConfigureServices中
//注入验证 2.0 services.AddAuthentication(options => { options.DefaultChallengeScheme = "MyCookieAuthenticationScheme"; options.DefaultSignInScheme = "MyCookieAuthenticationScheme"; options.DefaultAuthenticateScheme = "MyCookieAuthenticationScheme"; }) .AddCookie("MyCookieAuthenticationScheme", opt => { opt.LoginPath = new PathString("/login"); opt.AccessDeniedPath = new PathString("/login"); opt.LogoutPath = new PathString("/login"); opt.Cookie.Path = "/"; });
Configure中
app.UseAuthentication();
登录验证
public class UserTestController : Controller { [HttpGet("users")] [Authorize(Roles = "admin,system")] public IActionResult Index() { return View(); } [HttpGet("login")] public IActionResult Login(string returnUrl) { //1、如果登录用户已经Authenticated,提示请勿重复登录 if (HttpContext.User.Identity.IsAuthenticated) { return View("Error", new string[] { "您已经登录!" }); }else//记录转入地址 { ViewBag.returnUrl = returnUrl; return View();} }
[AllowAnonymous] [HttpPost("login")] public IActionResult Login(string username, string returnUrl) { //2、登录后设置验证 if (username == "gsw") { var claims = new Claim[]{ new Claim(ClaimTypes.Role, "admin"), new Claim(ClaimTypes.Name,"桂素伟") }; HttpContext.SignInAsync("MyCookieAuthenticationScheme",new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookie"))); //给User赋值 var claPris = new ClaimsPrincipal(); claPris.AddIdentity(new ClaimsIdentity(claims)); HttpContext.User = claPris; return new RedirectResult(returnUrl == null ? "users" : returnUrl); } else { return View(); } }
UI访问
//3、UI上访问验证信息 @if (User.IsInRole("abc")) { <p>你好: @User.Identity.Name</p> <a href="更高权限">更高权限</a> }
权限中间件
/// <summary> /// 权限中间件 /// </summary> public class PermissionMiddleware { /// <summary> /// 管道代理对象 /// </summary> private readonly RequestDelegate _next; /// <summary> /// 权限中间件构造 /// </summary> /// <param name="next">管道代理对象</param> /// <param name="permissionResitory">权限仓储对象</param> /// <param name="option">权限中间件配置选项</param> public PermissionMiddleware(RequestDelegate next) { _next = next; } /// <summary> /// 调用管道 /// </summary> /// <param name="context"></param> /// <returns></returns> public Task Invoke(HttpContext context) { return this._next(context); } }
自定义策略
/// <summary> /// 权限授权Handler /// </summary> public class PermissionHandler : AuthorizationHandler<PermissionRequirement> { /// <summary> /// 用户权限 /// </summary> public List<Permission> Permissions { get; set; } protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) { //赋值用户权限 Permissions = requirement.Permissions; //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息 var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext; //请求Url var questUrl = httpContext.Request.Path.Value.ToLower(); //是否经过验证 var isAuthenticated = httpContext.User.Identity.IsAuthenticated; if (isAuthenticated) { //权限中是否存在请求的url if (Permissions.GroupBy(g => g.Url).Where(w => w.Key.ToLower() == questUrl).Count() > 0) { var name = httpContext.User.Claims.SingleOrDefault(s => s.Type == requirement.ClaimType).Value; //验证权限 if (Permissions.Where(w => w.Name == name && w.Url.ToLower() == questUrl).Count() > 0) { context.Succeed(requirement); } else { //无权限跳转到拒绝页面 httpContext.Response.Redirect(requirement.DeniedAction); } } else { context.Succeed(requirement); } } return Task.CompletedTask; } }
自定义策略-JWT
/// <summary> /// 权限授权Handler /// </summary> public class PermissionHandler : AuthorizationHandler<PermissionRequirement> { /// <summary> /// 验证方案提供对象 /// </summary> public IAuthenticationSchemeProvider Schemes { get; set; } /// <summary> /// 自定义策略参数 /// </summary> public PermissionRequirement Requirement { get; set; } /// <summary> /// 构造 /// </summary> /// <param name="schemes"></param> public PermissionHandler(IAuthenticationSchemeProvider schemes) { Schemes = schemes; } protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) { 赋值用户权限 Requirement = requirement; //从AuthorizationHandlerContext转成HttpContext,以便取出表求信息 var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext; //请求Url var questUrl = httpContext.Request.Path.Value.ToLower(); //判断请求是否停止 var handlers = httpContext.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>(); foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync()) { var handler = await handlers.GetHandlerAsync(httpContext, scheme.Name) as IAuthenticationRequestHandler; if (handler != null && await handler.HandleRequestAsync()) { context.Fail(); return; } } //判断请求是否拥有凭据,即有没有登录 var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync(); if (defaultAuthenticate != null) { var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name); //result?.Principal不为空即登录成功 if (result?.Principal != null) { httpContext.User = result.Principal; //权限中是否存在请求的url if (Requirement.Permissions.GroupBy(g => g.Url).Where(w => w.Key.ToLower() == questUrl).Count() > 0) { var name = httpContext.User.Claims.SingleOrDefault(s => s.Type == requirement.ClaimType).Value; //验证权限 if (Requirement.Permissions.Where(w => w.Name == name && w.Url.ToLower() == questUrl).Count() <= 0) { //无权限跳转到拒绝页面 httpContext.Response.Redirect(requirement.DeniedAction); } } context.Succeed(requirement); return; } } //判断没有登录时,是否访问登录的url,并且是Post请求,并且是form表单提交类型,否则为失败 if (!questUrl.Equals(Requirement.LoginPath.ToLower(), StringComparison.Ordinal) && (!httpContext.Request.Method.Equals("POST") || !httpContext.Request.HasFormContentType)) { context.Fail(); return; } context.Succeed(requirement); } }