中间插件
中间件和Filter类似,不过Filter更加偏向于业务
1、定义中间插件,RequestDelegate 委托
public class RequestLoggerMiddleware { private readonly RequestDelegate _next; public RequestLoggerMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { try { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); await _next.Invoke(context); stopwatch.Stop(); Console.WriteLine($"请求地址:{context.Request.Path};请求相应时间:{stopwatch.ElapsedMilliseconds}ms"); if (context.Response.StatusCode == (int)StatusCodes.Status404NotFound) { var resultError = JsonConvert.SerializeObject(new { Ok=false,Data="action not found"}); await context.Response.WriteAsync(resultError); } } catch (Exception ex) { } }
public class RequestLoggerMiddleware { private readonly RequestDelegate _next; public RequestLoggerMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { try { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); await _next.Invoke(context); stopwatch.Stop(); Console.WriteLine($"请求地址:{context.Request.Path};请求相应时间:{stopwatch.ElapsedMilliseconds}ms"); } catch (Exception ex) { } } }
2、
public static class MiddlewareExtensions { public static IApplicationBuilder RequestLogger(this IApplicationBuilder builder) { return builder.UseMiddleware<RequestLoggerMiddleware>(); } }
3、使用中间件,一定要放在AddMvc之前,否则不起作用
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { AppDependencyResolver.Init(app.ApplicationServices); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } // Add management endpoints into pipeline app.UseCloudFoundryActuators(); app.UseLoggersActuator(); app.RequestLogger(); app.UseHttpsRedirection(); app.UseMvc(); }

浙公网安备 33010602011771号