Core知识整理
概述
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);
}
}
Core知识整理的更多相关文章
- Salesforce知识整理(一)之Lightning Web Component Tools
目录 LWC知识整理(一) 工具 Salesforce CLI Visual Studio Code(VS Code) Developer Hub(Dev Hub) 开启Dev Hub 相关资料 茶余 ...
- OpenCV&Qt学习之四——OpenCV 实现人脸检测与相关知识整理
开发配置 OpenCV的例程中已经带有了人脸检测的例程,位置在:OpenCV\samples\facedetect.cpp文件,OpenCV的安装与这个例子的测试可以参考我之前的博文Linux 下编译 ...
- js事件(Event)知识整理
事件(Event)知识整理,本文由网上资料整理而来,需要的朋友可以参考下 鼠标事件 鼠标移动到目标元素上的那一刻,首先触发mouseover 之后如果光标继续在元素上移动,则不断触发mousemo ...
- Kali Linux渗透基础知识整理(四):维持访问
Kali Linux渗透基础知识整理系列文章回顾 维持访问 在获得了目标系统的访问权之后,攻击者需要进一步维持这一访问权限.使用木马程序.后门程序和rootkit来达到这一目的.维持访问是一种艺术形式 ...
- Kali Linux渗透基础知识整理(二)漏洞扫描
Kali Linux渗透基础知识整理系列文章回顾 漏洞扫描 网络流量 Nmap Hping3 Nessus whatweb DirBuster joomscan WPScan 网络流量 网络流量就是网 ...
- wifi基础知识整理
转自 :http://blog.chinaunix.net/uid-9525959-id-3326047.html WIFI基本知识整理 这里对wifi的802.11协议中比较常见的知识做一个基本的总 ...
- 数据库知识整理<一>
关系型数据库知识整理: 一,关系型数据库管理系统简介: 1.1使用数据库的原因: 降低存储数据的冗余度 提高数据的一致性 可以建立数据库所遵循的标准 储存数据可以共享 便于维护数据的完整性 能够实现数 ...
- 【转载】UML类图知识整理
原文:UML类图知识整理 UML类图 UML,进阶必备专业技能,看不懂UML就会看不懂那些优秀的资料. 这里简单整理 类之间的关系 泛化关系(generalization) 泛化(generalize ...
- Linux进程管理知识整理
Linux进程管理知识整理 1.进程有哪些状态?什么是进程的可中断等待状态?进程退出后为什么要等待调度器删除其task_struct结构?进程的退出状态有哪些? TASK_RUNNING(可运行状态) ...
随机推荐
- php Glob() 使用 查找文件:
1. 取得所有的后缀为PHP的文件(加上路径)$file=glob('D:/phpStudy/WWW/prictue/*.php');print_r($file);//如果没有指定文件夹的话就是显示出 ...
- AVPass技术分析:银行劫持类病毒鼻祖BankBot再度来袭,如何绕过谷歌play的杀毒引擎?
背景 近期,一批伪装成flashlight.vides和game的应用,发布在google play官方应用商店.经钱盾反诈实验室研究发现,该批恶意应用属于新型BankBot.Bankbot家族算得上 ...
- 背水一战 Windows 10 (108) - 通知(Tile): application tile 基础, secondary tile 基础
[源码下载] 背水一战 Windows 10 (108) - 通知(Tile): application tile 基础, secondary tile 基础 作者:webabcd 介绍背水一战 Wi ...
- 设置HttponlyCookie解决mshtml编程无法获取验证码图片流
最近给客户做的项目有一个新需求,客户需要在打开的IE浏览器中做自动登录,登录的页面上有神兽验证码.解决验证码的方案是找第三方平台打码.这样就有一个问题,如何把正确的验证码传给第三方打码平台. 大家都知 ...
- Crontab和sudo中无法使用TensorFlow ImportError libcublas.so.9.0
最近因为特殊的原因重新安装了python,但是引发了一个很严重的问题--TensorFlow不好使了. 比如我下面这个执行文件test.py: import tensorflow as tf prin ...
- Linux — 文件、目录管理
目录与路径 . 此层目录 .. 上层目录 - 之前一个工作目录 ~ 主文件夹 ~ account 指定用户的主文件夹,account --账号名称 cd 切换目录 pwd (print worki ...
- Oracle开窗函数笔记及应用场景
介绍Oracle的开窗函数之前先介绍一下分析函数,因为开窗函数也属于分析函数 分析函数用于计算基于组的某种聚合值,它和聚合函数的不同之处是:对于每个组返回多行,而聚合函数对于每个组只返回一行. 上面是 ...
- 用Ajax遍历三级下拉框
用Ajax遍历三级下拉框 //通过一级分类的id查二级分类(记得在前端网页按钮绑定点击事件) function getSecondCategory(oneCategoryId){ alert(&quo ...
- ubuntu中环境变量文件/etc/profile、.profile、.bashrc、/etc/bash.bashrc之间的区别和联系
一 /etc/profile: 此文件为系统的每个用户设置环境信息,当用户第一次登录时,该文件被执行.并从/etc/profile.d目录的配置文件中搜集shell的设置.所以如果你有对/etc/pr ...
- 使用JDOM解析xml文档
一.使用JDOOM解析xml文档 准备工作 1.下载JDOM.jar 包 解析代码如下 import org.jdom2.Attribute; import org.jdom2.Document; i ...