【问题标题】:Custom Middleware doesn't handle exception with debug run ASP.NET CORE自定义中间件不处理调试运行 ASP.NET CORE 的异常
【发布时间】:2022-07-01 16:45:03
【问题描述】:

我正在尝试在我的 ASP.Net Core 5.0 项目中使用中间件进行异常处理,但它不处理异常,并且在抛出异常时调试会停止应用程序。

    
public class CustomExceptionMiddleWare
    {
        private readonly RequestDelegate _next;
        public CustomExceptionMiddleWare(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            var watch = Stopwatch.StartNew();
            try
            {
                string message = "[Request] HTTP " + context.Request.Method + " - " + context.Request.Path;
                Console.WriteLine(message);
                await _next(context);
                watch.Stop();
                message = "[Request] HTTP " + context.Request.Method + " - " + context.Request.Path + " responded " +
                    context.Response.StatusCode.ToString() + " in " + watch.Elapsed.TotalMilliseconds + " ms";
                Console.WriteLine(message);
            }
            catch (Exception ex)
            {
                watch.Stop();
                await HandleException(context, ex, watch);
            }
        }

        private Task HandleException(HttpContext context, Exception ex, Stopwatch watch)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;


            string message = "[Error]   HTTP" + context.Request.Method + " - " + context.Response.StatusCode +
                " Error Message " + ex.Message + " in " + watch.Elapsed.TotalMilliseconds + " ms";
            Console.WriteLine(message);


            var result = JsonConvert.SerializeObject(new { Error = ex.Message }, Formatting.None);
            return context.Response.WriteAsync(result);
        }
    }


    public static class CustomExceptionMiddlewareExtension
    {
        public static IApplicationBuilder UseCustomExceptionMiddleWare(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CustomExceptionMiddleWare>();
        }
    }
}

startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                //app.UseDeveloperExceptionPage();
                app.UseCustomExceptionMiddleWare();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "PatikaWebApi v1"));

            }

            
            //app.UseMiddleware<CustomExceptionMiddleWare>();
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseCustomExceptionMiddleWare();


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

控制器

 [HttpGet("{id}")]
        public IActionResult GetById(int id)
        {
            BookDetailViewModel result;
            GetBooksDetailQuery query = new GetBooksDetailQuery(_context,_mapper);
            query.BookId = id;
            GetBooksDetailQueryValidator validator = new GetBooksDetailQueryValidator();
            validator.ValidateAndThrow(query);
            result = query.Handle();
            return Ok(result);        
        }

当抛出异常时,中间件不使用调试模式处理异常。我搜索了解决方案,发现删除 app.UseDeveloperExceptionPage(); 行对我不起作用。我尝试更改管道但也没有工作。解决方案是什么?感谢您的关注。

错误是用户未处理的异常

【问题讨论】:

    标签: c# exception middleware .net-5


    【解决方案1】:

    从表面上看,我看不出为什么您的调试点没有被命中。但我建议在这种情况下使用过滤器而不是中间件。

    您可以查看 Jason Taylor 撰写的有关如何执行此操作的文章。这是他的github源代码链接。

    https://github.com/jasontaylordev/CleanArchitecture/blob/main/src/WebUI/Filters/ApiExceptionFilterAttribute.cs

    我还为你写了一个简化的例子。我希望这能解决您的问题。

    异常过滤器:

    using Microsoft.AspNetCore.Mvc.Filters;
    
    namespace Multitrust.API.Filters
    {
    public class ApiExceptionFilter : ExceptionFilterAttribute
    {
        public ApiExceptionFilter() 
        {
        }
    
    
        public override void OnException(ExceptionContext context)
        {
    
            HandleException(context);
        }
    
        private void HandleException(ExceptionContext context)
        {
            //Do stuff with the exception
        }
    
        }
    }
    

    Startup.cs:

        public void ConfigureServices(IServiceCollection services)
        {
    
            services.AddControllersWithViews(options =>
                options.Filters.Add(new ApiExceptionFilter()));
                
          //Bind other services...
    
         }
    

    如果您需要任何帮助,请告诉我。

    编码愉快!

    【讨论】:

      【解决方案2】:

      .NET core 中已经提供了一个中间件。 app.UseExceptionHandler。 您需要定义引发异常时的响应。

      我曾经写过一篇关于同一主题的简单文章。 看看吧。

      https://medium.com/@niteshsinghal85/how-i-have-handled-exception-globally-in-asp-net-core-api-7b8c2603af72.

      希望它能解决您的问题。

      【讨论】:

        猜你喜欢
        • 2021-08-06
        • 1970-01-01
        • 2019-11-10
        • 2020-09-23
        • 2018-06-07
        • 2012-01-01
        • 2019-01-24
        • 2020-05-19
        • 2014-05-06
        相关资源
        最近更新 更多