C#版本新语法-官网:
C#7:https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-7
C#8:https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-8
C#9:https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-9
一、C# 6新语法
1.1-自动属性初始化表达式


1.2-using static


1.3-Null 条件运算符

1.4-字符串内插

1.5-异常刷选器

1.6-nameof表达式

1.7-事件(发布订阅模式)



1.8-使用索引器初始化关联集合

二、C# 7新语法
2.1-Out变量


2.2-元祖




2.3-弃元


2.4-模式


2.5-本地方法

2.6-默认文本表达式

2.7-数字语法改进


2.8-命名实参



2.9-private protected访问修饰符-新复合访问修饰符

2.10-增强的泛型约束


2.11-通用的异步返回类型

三、C# 8新语法
3.1-默认接口方法


3.2-switch表达式
传统方式switch

新玩法

3.3-属性模式


3.4-元祖模式


3.5-位置模式


3.6-静态本地函数

3.7-异步流



四、C# 9新语法
4.1-记录
针对属性:


新的


针对方法:


4.2-顶级语句

4.3-对象声明(简化)

方法调用

4.4-静态修饰

4.5-模式匹配


4.6-为空判断

4.7-协变返回值
4.8-nint

4.9-Lambda 参数弃元

4.10-关系匹配

五、创建项目+Seesion传值
5.1-使用Session

5.2-Log4Net组件使用
(1)管理Nuget程序,下载【log4net】和【Microsoft.Extensions.Logging.Log4Net.AspNetCore】


(2)新建一个文件夹,保存log4net配置文件,一定要在【属性】中的 复制到输出目录 选择【始终复制】。

(3)在【Program.cs】文件的【CreateHostBuilder】方法中配置log4net。

也可以使用以下方式配置(在Startup中):
这里注意,别选择错了!然后就可以了。

六、程序的发布运行
6.1-项目的发布
(1)右击项目,选择【发布】


(2)选择【文件夹】

(3)选择要保存的路径,然后点击【完成】;

(4)点击【发布】,可以看到已经发布完成了。


6.2-项目的运行
6.2.1-IIS发布
- IIS直接简历网站,目录指向项目跟目录下的Debug、Net5文件;——不行
- 把项目发布后,目录指向项目发布目录;——可以的
6.2.2-ASP.NET Core跨平台原因

6.2.3-使用脚本启动网站


6.2.4-发布之后运行为什么样式加载不出404?
(1)需要在【startup.cs】文件的【Configure】方法中引入一个中间件。

七、命令参数读取+配置多种读取
7.1-配置文件读取(1)
在【startup.cs】文件中读取配置文件

在【控制器】中读取配置文件。
(1)先构造函数注入Configure

(2)写代码获取


7.2-配置文件读取(2)
(1)定义一个类,结构(数据类型、属性名)和配置文件中完全一致。

(2)在【Startup.sc】配置一下

(3)在控制器中,构造函数注入一个IOptions

(4)获得并返回值

(5)前端获取值


八、MVC开发
8.1-什么是MVC?
- V——View——视图:呈现给用户看到的内容(表现层)
- C——Controller——控制器:控制业务逻辑计算,调用服务,选择返回什么内容,可以返回视图,JSON、字符串等等。
- M——Model——视图模型:用作控制器和视图之间传递数据的载体。
8.2-cshtml文件
其实是一个类文件。
Razor混编:可以在cshtml上写 后台C#代码 + 前台html代码,混合起来写;
(1)可以引入命名空间

(2)直接写后台代码

(3)实现接口

(4)可以依赖注入

(5)可以添加特性Class

(6)定义方法并调用

(7)写单行代码、多行代码


(8)Razor表达式

(9)输出尖括号

(10)for循环

(11)在后台代码内部写HTML代码

8.3-如何解决修改视图后无需编译后即可生效?
修改视图,增加了html代码,不能马上生效,怎么办?使用中间件

1.引入Nuget包

2.在【Startup.cs】文件的票【ConfigureServices】方法中配置。

8.4-Razor布局
8.4.1-我们看到的页面组成到底有哪些内容?
答:包含了Layout的模板嵌套的返回的需要渲染的视图内容;
8.4.2-如何嵌套呢?
答:通过Layout中RendBody()方法做了替换;把返回的视图替换到模板也中,形成了一整块的内容;目的在于每一次返回不同的页面的时候,能够吧不变的视图部分,种以重用;这样就可以少些代码。

8.4.3-在模板页面导入了JQ,在视图页面使用JQ为什么报错?
注意:
- 在模板页中使用CSS/JS的时候,为了提高效率,会把Css引入在模板的上方,将JS写在模板的下方。页面嵌套到模板页后,就会出现在引用JS的上方调用JS,此时JS其实是调用不了的。

答:因为Script是写在下面的,先加载RenderBody,后加载JQ,所以会报错,解决方法如下:

九、Razor扩展-HTML控件
9.1-Html扩展控件(1)
本质:通过一个后台方法,返回一个【已经存在】的Html标签的字符串,浏览器在读取的时候,就读取成一个Html标签。
1.定义- /// <summary>
- /// 图片
- /// </summary>
- /// <param name="helper"></param>
- /// <param name="src"></param>
- /// <returns></returns>
- public static IHtmlContent Img(this IHtmlHelper helper,string src,string @class)
- {
- return new HtmlString($"<img src='https://www.cnblogs.com/{src}' class='{@class}'/>");
- }
复制代码 2.调用- @Html.Img("https://tpc.googlesyndication.com/simgad/3105023548593992165/downsize_200k_v1?w=200&h=200","border:1px solid red;")
复制代码 9.2-Html扩展控件(2)
通过一个后台方法,返回一个【不存在】的Html标签的字符串,在读取的时候,通过制后台方法,去生成我们制定的标签。
1.写一个扩展方法,定义一个普通类,类名建议以TagHelper结尾,加上特性;如果没有标记特性,视图中在调用的时候使用当前类名去掉TagHelper后缀得到的的字符串来调用。继承TagHelpre抽象类、或者实现接口ITagHelpr,二者选一起均可。然后实现接口Proccss方法。

2.在【_ViewImports.cshtml】进行注册

3.使用

9.3-Razor局部视图
1.创建一个局部视图

2.进行调用

9.3.1-局部视图的缺陷:
局部视图没有去访问控制器中的Action,所以不能完美的实现后台代码。可以使用视图组件解决。
9.4-视图组件-扩展定制
9.4.1-视图组件的优点?
- 呈现页面相应的某一部分而不是整个相应
- 包括在控制器和视图之间发现的关注分离和可测试性优势
- 可以具有参数和业务逻辑
- 通常在页面布局中调用
9.4.2-如何自定义视图组件?
(1)Rzaor组件对应的类需要以ViewComponent结尾,该类需要继承自ViewCompnent类。

(2)定义一个异步版本的InvokeAsync,可以自定义参数,IncokeAsync就是返回组件内容的方法。

(3)在Views/Shared文件下建立Components文件夹,在这个文件下创建一个和组件类名相同(如果加了特性,就按照特性上面的名称来)的文件夹,然后创建一个Default.cshtml视图。

注意:以上步骤可以不按照上面执行,我们可以随意新建一个视图,然后指定路径就可以了。

(4)调用

十、内置容器基本使用
10.1-什么是IOC?
把对象的创建,统一交给第三方容器来创建;
10.2-如何使用IOC?
(1)在【Startup.cs】的【ConfigureServices】中注册服务;注册抽象和具体的依赖关系;

(2)通过构造函数进行依赖注入,自动得到服务的实例;

(3)调用;

10.3-如何使用IOC?(第二种方法)
(1)在【Startup.cs】的【ConfigureServices】中注册服务;注册抽象和具体的依赖关系;

(2)通过构造函数进行依赖注入。

(3)调用;

10.4-在视图中使用IOC

10.4-什么是依赖注入?
DI依赖注入:IServiceCollection支持且支持构造函数注入。
如对象A依赖对象B,对象B依赖于对象C,就可以先构造对象C,然后传递给对象B,然后传递给对象A,然后得到具体的实例。可以支持无限层级的依赖注入,前提是先要先注入服务(注册抽象和具体的映射关系)。
10.5-IServiceCollection生命周期
那么在创建对象的时候, 不同的情况,需要让对象单例,每一次都创建新的对象实例,不同的作用于创建新的实例。
AddTransient:顺时声明周期,每次获取的都是不同的实例

AddSingleton:单例生命周期,在整个进程中获取的都是同一个实例

AddScoped:作用域生命周期(同一个作用域,获取的是同一个对象的实例,不同的作用域,获取的是不同的独对象实例)

建议:开发工作中,一般情况下,都是一个请求一个对象的实例,所以使用的是顺时声明周期(AddTransient)。
十一、Autofac容器
11.1-Autofac容器初识?
Autofac也是一款流行的IOC容器;
11.2-如何使用Autofac容器?
(1)管理Nuget程序包,下载并安装【Autofac】

(2)在【Startup.cs】的【ConfigureServices】中注册服务;

11.3-Autofac注入方式-构造函数注入


11.4-Autofac注入方式-属性注入


11.5-Autofac注入方式-方法注入


11.6-Autofac生命周期-瞬时生命周期(默认)
瞬时生命周期:每一次获取对象都是一个全新的实例,默认的生命周期。

11.7-Autofac生命周期-单例生命周期
单例声明周期:在整个进程中,对象永远都是同一个实例(SingleInstance)

11.8-Autofac生命周期-每个生命周期范围一个实例
每个生命周期范围一个实例:同一个生命周期范围内是同一个实例,不同的生命周期范围,实例不一样。(InstancePerLifetimeScope)

11.9-Autofac生命周期-每个匹配生命周期范围一个实例
语法:InstancePerMatchingLifetimeScope(名称)

11.10-Autofac生命周期-每个请求一个实例

11.11-Autofac支持配置文件
(1)管理Nuget包,引入3个程序集;

(2)新建一个配置文件【autofac.json】,记得将配置文件设置为:始终复制到目录。


(3)在【Startup.cs】的【ConfigureServices】中注册服务;

11.12-Autofac整合MVC
注意:Autofac是一个第三方容器;
(1)指定Autofac工厂替换默认工厂,在【Program.cs】中的【CreateHostBuilder】方法中指定。

(2)在【Startup.cs】类中增加一个【ConfigureContainer】方法,用来注册服务关系。- /// <summary>
- /// 增加一个方法:
- /// 整个方法被Autofac自动调用
- /// 负责注册各种服务
- /// </summary>
- /// <param name="services"></param>
- public void ConfigureContainer(ContainerBuilder containerBuilder) {
- containerBuilder.RegisterType<TestServiceA>().As<ITestServiceA>();
- containerBuilder.RegisterType<TestServiceB>().As<ITestServiceB>();
- containerBuilder.RegisterType<TestServiceC>().As<ITestServiceC>();
- containerBuilder.RegisterType<TestServiceD>().As<ITestServiceD>().PropertiesAutowired();
- containerBuilder.RegisterType<TestServiceE>().As<ITestServiceE>();
- }
复制代码 (3)通过控制器构造函数注入,获取实例。

这种方法也还能用:

11.13-Autofac支持控制器属性注入
(1)首先在【Startup.cs】中【ConfigureServices】方法中,指定控制器实例容器来创建,进行替换。

(2)创建一个类(特性);

(3)创建一个类,用来判断维度;

(4)在【Startup.cs】中创建一个【ConfigureContainer】方法,负责注册各种服务。

11.14-Autofac一个实例多实现的问题
注意:
- 如果一个抽象多个实例,都注册了,通过构造函数用抽象类型来获取实例,哪个是后面注册的,就能获得哪个,覆盖类型的。
- 如果一个抽象多个实例,都注册了,可以通过一个IEnumerable,当做构造函数参数,可以获取到左右注册的具体的实例。

一般使用以下方法:
(1)在【Startup.cs】中创建的【ConfigureContainer】方法中,注册资源和实现(单抽象、多实现)

(2)通过构造函数中,使用具体理性实理性做我参数,可以匹配到不同的具体类型实例。


(1)新建一个类,该类继承Module类,实现Load方法。

(2)与之前相同,不同的而方式:在【Startup.cs】中创建的【ConfigureContainer】方法中,注册资源和实现(单抽象、多实现)

11.15-Autofac通过抽象(接口)支持AOP(面向切面编程-做应用型系统)
AOP-面向切面编程:不用修改之前代码的基础上,可以动态的在某个动作之前加一些操作,动态的在某一个动作之后做点什么事。
(1)管理Gurget程序包,下载【Castle.Core】包,该包用来动态代理。

(2)创建一个类为【CustomAutofacAop】,该类继承自【IInterceptor】接口,并实现接口中的【Intercept】方法。

(3)在服务的抽象上面做一个标记,这个标记是用来:支持AOP扩展能够生效。

(4)因为这个【CustomAutofacAop】实例也是通过Autofac的IOC来做的,所以需要在【Startup.cs】中创建的【ConfigureContainer】方法中,注册服务,让Autofac支持AOP。

11.16-Autofac通过类支持AOP
(1)管理Gurget程序包,下载【Castle.Core】包,该包用来动态代理。

(2)创建一个类为【CustomAutofacAopClass】,该类继承自【IInterceptor】接口,并实现接口中的【Intercept】方法。

(3)在类上面做一个标记,这个标记是用来:支持AOP扩展能够生效。

(4)因为这个【CustomAutofacAop】实例也是通过Autofac的IOC来做的,所以需要在【Startup.cs】中创建的【ConfigureContainer】方法中,注册服务,让Autofac支持AOP。

11.17-Autofac单抽象多实现构造函数注入(MVC)
(1)在【Startup.cs】中创建的【ConfigureContainer】方法中,注册服务。

(2)在控制器中调用。

11.18-Autofac单抽象多实现属性注入
(1)道理和上面是一样的,可以吧Autofac上下文当做属性来注入。

(2)在使用的时候,通过Autofac上下文+不同注册的标识,获取到不同的具体实例。

十二、Filter过滤器
12.1-.NET5中5个Filter
- AuthorizationFilter:鉴权授权
- ResourceFilter:资源
- ExceptionFilter:异常
- ActionFilter:方法
- ResultFilter:结果
12.2-ActionFilter
1.自定义一个CusotmActionFilterAttribute

2.将特性标记在控制器中的某个方法上。

3.执行顺序如下:
- 执行控制器构造函数
- 执行CusotmActionFilterAttribute类的OnActionExecuting()方法
- 执行Action
- 执行CusotmActionFilterAttribute类的OnActionExecuted()方法
12.3-ActionFilter的多种使用
1.通过实现IActionFilter接口来完扩展

2.通过继承ActionFilterAttribute(系统提供的实现),根据不同的方法,达到自己的需求。

3.异步版本的实现,通过实现IAsyncActionFilter接口来实现。

12.4-ActionFilter的应用(日志处理)+依赖注入
1.做记录日志;ActionFilter比较靠近Action,日志记录就可以记录到Action内部做的一些处理。
(1)通过Log4net完成日志记录,需要注入Logger。

12.5-Filter的多种注入和特点
(1)[CustomActionFilter]:Filter必须是无参数构造函数
(2)[TypeFilter(typeof(CusotmLogFilterAttribute))]:可以没有无参数构造函数,可以支持依赖注入。
(3) [ServiceFilter(typeof(CusotmLogFilterAttribute))]:可以没有无参数构造函数,可以支持依赖注入。但是如果要使用这个,必须在【Startup.cs】中创建的【ConfigureContainer】方法中,注册服务注册一下;


(4)问:依赖注入是如何支持的?
答:IOC来做到的
12.6-ServiceFilter_TypeFilter的原理/扩展定制FilterFacoty
1.为什么可以使用ServiceFilter/TypeFilter都可以支持依赖注入呢?--是IOC容器来完成。
(1)自定义一个特性类,继承Attribute,实现接口IFilterFactory,实现接口中的方法;通过构造函数传递需要实例化的特性的Type类型;在实现接口中,通过Type获取到实例;

(2)标记在Action中。

12.7-Filter生效范围和控制执行顺序
12.7.1-Filter生效范围
- 标记在Action上,就只对当前Action生效。
- 标记在Controller上,就对改Controller上所有的Action生效。
- 全局注册,对于当前整个项目中的Actioin都生效(在【Startup.cs】中创建的【ConfigureServices】方法中进行全局注册)。

12.7.2-Filter的执行顺序
问:如果有三个ActionFilter,分别注册全局、控制器、Action;执行顺序如何呢?
答:先执行全局——>控制器——>Action——>控制器——>全局

可以理解为俄罗斯套娃
12.7.3-改变Filter的执行顺序
(1)将全局、控制器、Action的类继承自ActionFilterAttribute;

(2)使用是传入Order参数,值越小越先执行。

12.7.4-在自定义扩展中改变Filter的执行顺序

12.7-ResourceFilter扩展定制做缓存(为缓存而生)

(1)自定义一个特性类,继承Attribute,实现接口IResourceFilter,实现接口中的方法;

(2)标记在Action中;

12.8-Filter匿名
问题:如果全局注册,Filter生效于所有的Action,如果有部分Action我希望你不生效,怎么办呢?
匿名:可以避开Filter的检查;
如何支持自定义的Filter匿名:
(1)自定义一个特性类,继承Attribute。

(2)需要在需要匿名的Filter内部,检查是否需要匿名(检查是否标记的有匿名特)如果有就避开。

(3)使用Action。

12.9-ExceptionFilter-异常处理
(1)自定义一个CustomExceptionAttribute,继承Attribute,实现IExceptionFilter接口。
- 实现方法,先判断,异常是都被处理过,如果没有被处理过,就处理。
- 分情况处理:1.如果是ajax请求,就返回JsonReulst,如果不是Ajax,就返回错误页面。
- public class CustomExceptionAttribute : Attribute, IExceptionFilter
- {
- private readonly IModelMetadataProvider _modelMetadataProvider = null;
- /// <summary>
- /// 依赖注入:Model元数据的驱动
- /// </summary>
- public CustomExceptionAttribute(
- IModelMetadataProvider modelMetadataProvider
- ) {
- _modelMetadataProvider = modelMetadataProvider;
- }
- /// <summary>
- /// 当异常发生的时候出发到这里来
- /// </summary>
- /// <param name="context"></param>
- public void OnException(ExceptionContext context)
- {
- //判断异常有没有被处理过
- if (context.ExceptionHandled == false) {
- //没有处理过,在这里开始处理
- //如果是Ajax请求(看看Header是不是XMLHttpRequest)
- if (this.IsAjaxRequest(context.HttpContext.Request))
- {
- //中断式:如果对Result赋值,请求到这里结束了,不在继续Action
- context.Result = new JsonResult(new
- {
- Result = false,
- Msg = context.Exception.Message
- });
- }
- else {
- //跳转到异常页面
- var result = new ViewResult { ViewName = "~/Views/Errors.cshtml" };
- result.ViewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
- result.ViewData.Add("Exception", context.Exception);
- result.ViewData.Add("ErrDate", DateTime.Now);
- //中断式:如果对Result赋值,请求到这里结束了,不在继续Action
- context.Result = result;
- }
- context.ExceptionHandled = true;//指定异常已经被处理了
- }
- }
- /// <summary>
- /// 判断是不是Ajax请求
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- private bool IsAjaxRequest(HttpRequest request)
- {
- string header = request.Headers["X-Requested-With"];
- return "XMLHttpRequest".Equals(header);
- }
- }
复制代码 (2)注册到Action上,只对Action生效。

一般不会注册到Action上,一般会注册到全局(在【Startup.cs】中创建的【ConfigureServices】方法中进行全局注册)。

问题:ExceptionFilter能捕捉到哪些异常?能捕获到所有异常吗?
12.10-ExceptionFilter-异常捕捉覆盖
- 控制器实例化异常——能
- 异常发生在Try-cache中——不能,因为异常已经被捕捉到了
- 在视图中发生异常——不能
- 在Service层(业务逻辑层)中发生异常——能
- 在Action中发生异常——能
- 请求错误路径异常——不能(但是可以通过中间件解决)
在【Startup.cs】中创建的【Configure】方法中进行使用,只要状态不是200,就可以处理。- #region 捕捉异常的补充
- //只要不是200,都能进来
- app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");
- app.UseExceptionHandler(errorApp => {
- errorApp.Run(async context =>
- {
- context.Response.StatusCode = 200;
- context.Response.ContentType = "text/html";
- await context.Response.WriteAsync("<html lang="en"><body>\r\n");
- await context.Response.WriteAsync("Error!!!
- \r\n");
- var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
- Console.WriteLine("------------------------------------------------");
- Console.WriteLine($"{ exceptionHandlerPathFeature?.Error.Message}");
- Console.WriteLine("------------------------------------------------");
- if (exceptionHandlerPathFeature?.Error is FileNotFoundException) {
- await context.Response.WriteAsync("File error thrown!
- \r\n");
- }
- await context.Response.WriteAsync("<a target="_blank" href="/">Home</a>
- \r\n");
- await context.Response.WriteAsync($"<p>{ exceptionHandlerPathFeature?.Error.Message}</p>
- \r\n");
- await context.Response.WriteAsync("</body></html>\r\n");
- await context.Response.WriteAsync(new string(' ', 512));//IE padding
- });
- });
- #endregion
复制代码 12.11-ReusltFilter-结果Filter

(1)创建ResultFilter
自定义一个CustomResultFilterAttribute,继承Attribute,实现IResultFilter接口- public class CustomResultFilterAttribute : Attribute, IResultFilter
- {
- /// <summary>
- /// 在渲染视图之前执行
- /// </summary>
- /// <param name="context"></param>
- public void OnResultExecuting(ResultExecutingContext context)
- {
- Console.WriteLine("在喧嚷视图之前执行");
- }
- /// <summary>
- /// 渲染视图之后执行
- /// </summary>
- /// <param name="context"></param>
- public void OnResultExecuted(ResultExecutedContext context)
- {
- Console.WriteLine("渲染视图之后执行");
- }
- }
复制代码 (2)在Action上标记、使用

12.11-ReusltFilter应用-开发双语言系统功能
双语言系统其实就需要两个视图,要根据语言的不同,来选择不同的视图;因为在渲染视图之前,会进入到OnResultExecuting方法,就可以在这个方法中确定究竟使用哪一个视图文件。

十三、权限验证
13.1-基于Seesion/Cookies的权限认证
为了拦截一些操作:
- 传统的授权方式:Seesion、Cookies来完成:
- 在请求某个Action之前来做校验,验证当前操作者是否登录过,登录过就有权限。
- 如果没有权限就调到到登录页面去。
- AOP-Filter、ActionResult
13.1.1-传统的登录需要匿名
当注册全局权限验证码的时候,需要将Login取消权限验证,不然会产生这个错误:

解决:
(1)在【CustomActionAuthrizaFilterAttribute】中写代码写上这个代码支持匿名,继承自Attribute,实现IActionFilter接口。

(2)在Login的Action写上这个特性。

13.2-基于鉴权授权
通过中间件来支持;

(1)在【Startup.cs】中创建的【Configure】方法中进行中间件,使用中间件使用在App.UseRouting()之后,在app.UseEndpoints()之前。- #region 第一步:告诉框架说我要使用鉴权授权功能
- app.UseAuthentication();//鉴权:检测有没有登录,登录的是谁,赋值给User
- app.UseAuthorization();//授权:检测有没有权限,是否能够访问后续的页面
- #endregion
复制代码 (2)在【Startup.cs】中创建的【ConfigureServices】方法中增加一个AddAuthentication。- #region 增加一个授权AddAuthentication
- //用Cookie
- services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
- {
- //如果授权是被,就跳转到这个路径中
- options.LoginPath = new PathString("Eighth/Login");
- });
- #endregion
复制代码 (3)指定哪些Action需要做鉴权授权,直接标记特性;可以标记在控制器、Action,也可以标记在全局。

(4)在控制器的Login登录方法中修改如下:- #region 鉴权:鉴权,检测有没有登录,登录的是谁,赋值给User
- //rolelist 是登录成功后用户的角色---是来自于数据库的查询;不同的用户会查询出不同的角色;
- var rolelist = new List<string>() {
- "Admin",
- "Teacher",
- "Student"
- };
- //ClaimTypes.Role就是做权限认证的标识;
- var claims = new List<Claim>()//鉴别你是谁,相关信息
- {
- new Claim(ClaimTypes.Role,"Admin"),
- new Claim(ClaimTypes.Name,name),
- new Claim("password",password),//可以写入任意数据
- new Claim("Account","Administrator"),
- new Claim("role","admin"),
- new Claim("admin","admin"),
- };
- foreach (var role in rolelist)
- {
- claims.Add(new Claim(ClaimTypes.Role, role));
- }
- //将用户放在ClaimsPrincipal里面去了;相当身份证,将信息写到身份证里面去;
- ClaimsPrincipal userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));
- HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
- {
- ExpiresUtc = DateTime.UtcNow.AddMinutes(30),//过期时间:30分钟
- }).Wait();
- #endregion
复制代码
(5)当注册到控制器上、或者注册到全局上,又会出现这样的问题。

解决:在Login的Action上加上匿名特性,这个匿名是来自于框架的;- [AllowAnonymousAttribute] //匿名
复制代码 13.3-鉴权授权-角色授权(目前看是将角色定义死了)
不同的用户,可能会存在不同的角色,然而不同的角色在访问不同的页面的时候,需要做不同的拦截。——角色授权其实就是通过角色不同,做不通的权限拦截。
1.保证上一个(13.2)代码是不变。
2.在Action需要加上对应拥有访问该视图的角色。

当访问【Index03】时,会被拦截,跳转到拦截页面:

13.4-鉴权授权-策略授权
之前的角色授权是在代码中把【角色】定义死了,我们更希望能够自己来完成校验逻辑:
(1)创建一个类为【CustomAuthorizationHandler】,这个类专用来检验逻辑的,要求继承自【AuthorizationHandler】泛型类(泛型类中要求实现【IAuthorizationRequirement】接口:见步骤2)然后在CustomAuthorizationHandler类中实现【HandleRequirementAsync】抽象方法,写逻辑。- public class CustomAuthorizationHandler : AuthorizationHandler<CustomAuthorizationRequirement>
- {
- public CustomAuthorizationHandler() {
- }
- /// <summary>
- /// 实现抽象方法
- /// </summary>
- /// <param name="context"></param>
- /// <param name="requirement"></param>
- /// <returns></returns>
- protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomAuthorizationRequirement requirement)
- {
- if (requirement.Name == "Policy01") {
- //策略1的逻辑
- }
- if (requirement.Name == "Policy02")
- {
- //策略2的逻辑
- }
- if (requirement.Name == "Policy03")
- {
- //策略3的逻辑
- }
- if (true) {
-
- }
- //在这里可以定义自己的规则
- {
- /*
- 其实这里可以去数据库里面做一些查询,然后根据用户的信息,做计算:如果符合就context.Succd(requirement)
- 否则就Task。CompletedTask
- */
- }
- //context.User 鉴权成功(登录成功后),用户的信息
- var role = context.User.FindFirst(u => u.Value.Contains("admin"));
- if (role != null) {
- context.Succeed(requirement);//验证通过了
- }
- return Task.CompletedTask;//验证不通过
- }
- }
复制代码 (2)创建一个为类【CustomAuthorizationRequirement】,改类实现【IAuthorizationRequirement】接口,用来放在AuthorizationHandler泛型类中。

(3)怎么让其生效?在【Startup.cs】中创建的【ConfigureServices】方法中注册支持策略授权,也可以支持多种策略认证。- #region 支持多种策略认证
- services.AddAuthorization(options =>
- {
- options.AddPolicy("customPolicy", policy =>
- {
- policy.AddRequirements(new CustomAuthorizationRequirement("Policy01"));
- });
- });
- services.AddAuthorization(options =>
- {
- options.AddPolicy("customPolicy01", policy =>
- {
- policy.AddRequirements(new CustomAuthorizationRequirement("Policy02"));
- });
- });
- services.AddAuthorization(options =>
- {
- options.AddPolicy("customPolicy02", policy =>
- {
- policy.AddRequirements(new CustomAuthorizationRequirement("Policy03"));
- });
- });
- #endregion
- //注册支持策略授权
- services.AddSingleton<IAuthorizationHandler, CustomAuthorizationHandler>();
复制代码 十四、跨平台本质
- web应用程序是一个控制台;——Main程序的入口

跨平台的原因在于框架已经内置了一个主机,只要是程序启动,就是启动了主机,就可以监听端口;请求来了,只要是请求这个端口,主机就可以相应,所以无论是Windows还是在Linux下开发,都是要第一步完成环境的;这样就不同拘泥于在Windows还是Linux上。
十五、中间件
15.1-什么是中间件?
- 中间件的执行,是一个俄罗斯套娃;
- 先Use先执行,每一次Use一个中间件,其实就是在之前的基础上,套了一层;
- 请求来了以后,真正执行的时候,是一层一层的内部执行,在执行出来。
增加程序的扩展性:
如果想要增加一层,直接增加一个中间件就可以来完成。
15.2-常用的中间件
15.2.1-app.Run:中断式,只要使用当前中间件,后面的中间件都不执行;

15.2.2-app.Map:判断路径中包含什么内容。

15.2.3-app.MapWhen:判断式,两个委托,第一个委托做为判断条件内容,第二个委托,是要执行的逻辑

15.3-中间件扩展-引用
(1)中间件的内容可以独立开,放在一个独立的类中,需要有一定的规则如下(创建了3个中间件):- /// <summary>
- /// 要求构造函数带有RequestDelegate参数类型——目的是为了得到下一个中间件;
- /// 必须包含async Task Invoke方法,方法参数为HttpContext
- /// </summary>
- public class FirstMiddleware
- {
- private readonly RequestDelegate _next;
- /// <summary>
- /// 构造函数
- /// </summary>
- /// <param name="next"></param>
- public FirstMiddleware(RequestDelegate next) {
- _next = next;
- }
- public async Task Invoke(HttpContext context) {
- await context.Response.WriteAsync($"<h1 style='color:red'>{nameof(FirstMiddleware)}——Hello Word Start</h1>");
- await _next(context);
- await context.Response.WriteAsync($"<h2 style='color:blue'>{nameof(FirstMiddleware)}——Hello Word End</h1>");
- }
- }
复制代码 (2)在【Startup.cs】中创建的【Configure】方法中通过以下方法使用中间件:

十六、EF Core
16.1-EF Core可以做什么?
通过实体和数据库的映射,可以通过实体的操作完成对数据的操作。
映射:
16.2-DB First(数据库优先)
DB First:现有数据库,然后通过映射得到视图(和数据库的表对应);
(1)创建一个控制台应用程序,用来操作并测试。

(2)管理Nuget包,安装对应需要的包。


 - Install-Package Microsoft.EntityFramewrorkCore
- Install-Package Microsoft.Entit3FramewrorkCore.Sqlserver
- Install-Package Microsoft.EntityFramewrorkCore.Tools
- 工具--Nuget包管理器--程序包管理器控制台-命令执行(建议使用这种):
- Scaffold-DbContext "Data Source=.;Initial Catalog=CovidAPI;User ID=sa;Password=3344520" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Entity -Force -Context CovidAPIDbContext -ContextDir /
- --可以简写为:
- Scaffold-DbContext "Data Source=.;database=CovidAPI;uid=sa;pwd=3344520" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Entity
- 命令参数:
- -0utputDir 实体文件所存放的文件目录
- -ContextDir DbContext文件存放的目录
- -Context DbContext文件名
- -Schemas 需要生成实体数据的数据表所在的模式
- -Tables 等需要生成实体数据的数据表的集合
- -DataArnotations
- -UseDatabaseNames 直接使用数据库中的表名和列名(某些版本不支持)
- -Force 强制执行,重写已经存在的实体文件
复制代码 (3)将【EFCore.DbFirst】设置为启动项目,并在【程序包管理器控制台】中选中摸默认项目为【EFCore.DbFirst】,然后执行以上命令:

命令执行完毕,然后会根据数据库中的表生成以下实体和DbContext:

16.3-Code First(代码优先-迁移)
迁移:代码优先,先有代码再有数据库;数据库随着业务变化迁移改变。
迁移命令:

(1)可以通过EFCore代码有的API从代码生成数据库。

(2)可以通过迁移命令生成数据库。
2.1-需要引入程序包

2.2-将【EFCore.CodeFirst】设置为启动项目,并在【程序包管理器控制台】中选中摸默认项目为【EFCore.CodeFirst】,然后执行对应的命令:

然后可以看到生成了迁移文件和快照文件。

16.4-EFCore抓取SQL语句
16.4.1-日志输出
(1)打开Nuget包安装日志输出包。

(2)在数据上下文对象中的【OnConfiguring】方法中进行配置。

16.4.2-SQL Srever Profiler工具
(1)在SQL Srever数据库中【工具】——>【SQL Server Profiler】。

(2)打开之后进行数据库连接,和服务器是同一个服务器。

(3)选择模板和事件。


16.5-EFCore-LinqQuery(LINQ查询)
- #region 其他查询
- using (CovidAPIDbContext context = new CovidAPIDbContext())
- {
- //Lambda查询
- {
- var idlist = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 134, 46, 23, 46, 34 };//in查询
- var list = context.Employees.Where(u => idlist.Contains(u.Id));//in查询
- foreach (var item in list)
- {
- Console.WriteLine(item.Name);
- }
- }
- //LINQ查询
- {
- var list = from u in context.Employees
- where new int[] { 1, 2, 3, 4, 5, 6, 7, 8 }.Contains(u.Id)
- select u;
- foreach (var item in list)
- {
- Console.WriteLine(item.Name);
- }
- }
- //一般用于分页:Skip、Take——跳过第一条2,取2条
- {
- //var list = (from u in context.Employees
- // where new int[] { 1, 2, 3, 4, 5, 6, 7, 7 }.Contains(u.Id)
- // orderby u.Id
- // select new
- // {
- // Name = u.Name,
- // Img = u.PictureUrl
- // }).Skip(1).Take(2);
- //foreach (var item in list)
- //{
- // Console.WriteLine(item.Name);
- //}
- }
- //多条件
- {
- var list = context.Employees.Where(u => u.Name.StartsWith("三") && u.Name.EndsWith("三哈"))
- .Where(u => u.Name.StartsWith("张"))
- .Where(u => u.Name.Length < 5)
- .OrderBy(u => u.Id);
- foreach (var item in list)
- {
- Console.WriteLine(item.Name);
- }
- }
- //连接查询
- {
- var list = (from u in context.Employees
- join c in context.Departments
- on u.DepartmentId equals c.Id //注意:条件不能写 "==" 等于号,要使用equals
- where new int[] { 1, 2, 3, 4, 5, 6, 7 }.Contains(u.Id)
- select new
- {
- Id = u.Id,
- Nmae = u.Name,
- Bumen = c.Name
- }).OrderBy(u => u.Id);
- foreach (var item in list)
- {
- Console.WriteLine($"{item.Id}---{item.Nmae}---{item.Bumen}");
- }
- }
- //左连接
- //没有右连接,如果要做右连接,就把顺序调换一下就行了
- {
- var list = (from u in context.Employees
- join c in context.Departments on u.DepartmentId equals c.Id
- into ucList
- from uc in ucList.DefaultIfEmpty()
- where new int[] { 1, 2, 3, 4, 5, 6 }.Contains(u.Id)
- select new
- {
- Id = u.Id,
- Nmae = u.Name,
- Bumen = uc.Name
- }).OrderBy(u => u.Id);
- foreach (var item in list)
- {
- Console.WriteLine($"{item.Id}---{item.Nmae}---{item.Bumen}");
- }
- }
- #endregion
- }
复制代码 16.5-EFCore-执行查询、修改SQL语句
- #region 如果遇到非常复杂的查询——建议直接写SQL语句
- using (CovidAPIDbContext context = new CovidAPIDbContext()) {
- //查询
- {
- try
- {
- string sql1 = @"select * from dbo.Employees where Id > @Id";
- SqlParameter parameter1 = new SqlParameter("@Id", 4);
- var query = context.Employees.FromSqlRaw<Employee>(sql1, parameter1);
- foreach (var item in query) {
- Console.WriteLine(item.Name);
- }
- }
- catch (Exception ex) {
- Console.WriteLine(ex.Message);
- throw;
- }
- }
- //修改
- {
- string sql2 = @"update dbo.Employees set Name ='修改update' where id=@id";
- SqlParameter parameter2 = new SqlParameter("@id", 4);
- int flg = context.Database.ExecuteSqlRaw(sql2, parameter2);
- }
- }
- #endregion
复制代码 16.6-EFCore-State(动态跟踪)
增删改的动作是统一由SavaChanges以后才落实到数据库中去的:
数据库的增删改动作都是统一由SavaChanges之后,统一提交到数据库,是通过状态跟踪,任何一个增删改查的操作都会记录一个状态在内存中,增删改查的状态,一旦SavaChanges,就根据状态落实到数据库中去。- // 摘要:当前这个实体没有被上下文所跟踪
- Detached=0,
- // 摘要:实体正在被上下文跟踪,并且存在于数据库中,他的数据库中的数据没有被更改。
- Unchanged=1,
- // 摘要:实体被上下文跟踪,并且存在数据库中,并已标记从数据库中删除,并还没有删除。
- Deleted=2,
- // 摘要:实体被上下文跟踪,部分或他的所有属性都已经被修改。
- Modified=3,
- // 摘要:实体被上下文跟踪,但在数据库中还不存在。
- Added=4
复制代码
注意:
状态跟踪实现了增删改便捷,但是也会有性能消耗;因为每次都要去和内存的副本的状态去做比较的。
16.7-EFCore-事务(调优小技巧)
SavaChanges就是保证事务的,多个对于数据库的操作,统一SavaChanges,就是开启了一个事务的。
EF Core自带的两个事务:
(1)SavaChanges
(2)IDbContextTransaction

16.8-EFCore-调优小技巧
(1)尽量不要进行Tolist();

(2)尽量不要使用FirstOrDefault,要使用Find进行查询。

(3)只做查询时,不需要进行增删改,就去掉状态跟踪。

全局取消

十七、EFCore整合-分层架构
17.1-分层架构

- 没有分层的缺点:
- 职责不清晰
- 如果有一处修改,可能会导致需要重新修改,需要重新测试。
- 分层的优点:
- 职责更清晰
- 需求的变更不同修改全部代码
- 人员更好调配——让更专业的人做专业的事。
- 三层架构:
- UI:展示给用户,视图层
- BLL:业务逻辑层
- DAL:数据访问层
分层以后:要求不能跨层调用,UI层——BLL层——DAL层
17.2-依赖注入
支持依赖注入:必须有抽象,依赖抽象而不是依赖实现细节。
原文地址:https://www.cnblogs.com/kimiliucn/p/17613434.html
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |