自定义中间件(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();
}
复制代码

 

posted @   一事冇诚  阅读(2136)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示