public class MyMiddleware { //private IConfiguration _configuration; //第一步: private RequestDelegate _next;// using Microsoft.AspNetCore.Http; //加一个构造方法.构造方法第一个参数必须是RequestDelegate类型,表示为中间件类型,即是表示为下一个中间件。定义中间件时必须包含对下一个中间件的引用。 public MyMiddleware(RequestDelegate next) { _next = next;//通过私有字段去接收下一个中间件的引用,因为我们在其他地方需要用这个下一个中间件next。这步是关键,必须的有,这个实现把中间件串联起来 //_configuration = configuration; } //第二步增加Task InvokeAsync(HttpContext context)方法,方法名称固定为InvokeAsync,返回值为Task public async Task InvokeAsync(HttpContext context) { await context.Response.WriteAsync("test"); await _next.Invoke(context); } }
接下来在StartUp.cs文件的Configure方法中注入启用中间件。使用UseMiddleware方法注册:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseMiddleware<MyMiddleware>();//启用中间件 app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }