自定义中间件(MiddleWare)
原文链接: https://www.cnblogs.com/ysmc/p/16512669.html
以下代码自定义简单的异常处理中间件Demo
ExceptionMiddleWare
1 public class ExceptionMiddleWare 2 { 3 private readonly RequestDelegate _next; 4 public ExceptionMiddleWare(RequestDelegate next) 5 { 6 _next = next; 7 } 8 public async Task Invoke(HttpContext context) 9 { 10 try 11 { 12 await _next.Invoke(context); 13 } 14 catch (Exception ex) 15 { 16 await HandleExceptionAsync(context, ex); 17 } 18 } 19 private async Task HandleExceptionAsync(HttpContext context, Exception exception) 20 { 21 var time = DateTime.Now.ToString("yyyyMMddhhmmss"); 22 FileHelper.WriteInformationFile(exception.ToString(), Path.Combine("Errlog", DateTime.Now.ToString("yyyyMMdd"), time + ".txt")); 23 var response = context.Response; 24 response.ContentType = "application/json"; 25 response.StatusCode = (int)HttpStatusCode.InternalServerError; 26 await response.WriteAsync(JsonConvert.SerializeObject(new 27 { 28 // customize as you need 29 error = new 30 { 31 message = "系统错误,请联系管理员", 32 errfile = time 33 } 34 })); 35 } 36 }
ExceptionMiddleWareBuilder
public static class ExceptionMiddleWareBuilder { public static IApplicationBuilder ExceptionMiddleWare(this IApplicationBuilder builder) => builder.UseMiddleware<ExceptionMiddleWare>(); }
Startup
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.HttpRequestMiddleWare(); if (env.IsDevelopment()) { //app.UseDeveloperExceptionPage(); app.ExceptionMiddleWare(); } else app.ExceptionMiddleWare(); app.UseMvc(); }
本文来自博客园,作者:一事冇诚,转载请注明原文链接:https://www.cnblogs.com/ysmc/p/16512669.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?