# aspnetcore_study **Repository Path**: defa/aspnetcore_study ## Basic Information - **Project Name**: aspnetcore_study - **Description**: asp.net core 学习 - **Primary Language**: C# - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2018-01-24 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # aspnetcore_study # 1. MiddleWare ## Demo1 模拟中间件的实现方式 ``` class Program { static void Main(string[] args) { IApplicationBuilder appBuidler=new ApplicationBuilder(null); appBuidler.UseMiddleware(); appBuidler.Use(async (context,next)=>{ await Console.Out.WriteLineAsync("Call before next."); await next(context); await Console.Out.WriteLineAsync("Call after next."); }); appBuidler.Run(async (context)=>{ await Console.Out.WriteLineAsync("hello world!"); }); var app=appBuidler.Build(); var response=app.Invoke(new RequestContext(){ Url="http://localhost"}); response.Wait(); Console.ReadLine(); } } //LogMiddleWare类 public class LogMiddleWare { private readonly RequestDelegate _next; public LogMiddleWare(RequestDelegate next) { if (next == null) { throw new ArgumentNullException(nameof(next)); } _next = next; } public async Task Invoke(RequestContext context){ await Console.Out.WriteLineAsync("before log!"); await _next(context); await Console.Out.WriteLineAsync("after log!"); } } ``` ``` //RequestContext 类模拟了请求上下文 public class RequestContext { public string Url{ get; set;} } //RequestDelegate模拟了这一类请求的委托 public delegate Task RequestDelegate(RequestContext context); //IApplicationBuilder用来创建注册委托和并创建应用 public interface IApplicationBuilder { IServiceProvider ApplicationServices{get;set;} void Add(Func middleware); RequestDelegate Build(); } //ApplicationBuilderExtension对IApplication进行了一些方法的扩展,UseMiddleWare,Use,Run等方法 void UseMiddleware(this IApplicationBuilder builder, params object[] args) void Use(this IApplicationBuilder builder,Func func) void Run(this IApplicationBuilder builder,Func last) ``` ## Demo2 模拟 WebHostBuilder ``` static void Main(string[] args) { var host = new WebHostBuilder() .UseTestServer() .Configure(app => { app.UseMiddleware(); app.Use(async (context, next) => { await Console.Out.WriteLineAsync(context.Url + "Call before next."); await next(context); await Console.Out.WriteLineAsync(context.Url + "Call after next."); }); app.Run(async (context) => { await Console.Out.WriteLineAsync("hello world!"); }); }) .Build() host.Run(); Console.ReadLine(); } ```