为什么错误处理中间件在 asp 中不起作用

Why Error handling middleware does not work in asp

提问人:ruddnisrus 提问时间:7/16/2021 更新时间:7/16/2021 访问量:226

问:

我的简单应用程序错误处理中间件有问题......当我篡改sql连接字符串时,我收到错误,但我的中间件没有抓住它......有人知道为什么吗?

{
    public class ErrorHandlingMiddleware : IMiddleware // we need to add it to tell ASP that this class is middleware
    {

        public ErrorHandlingMiddleware()
        {

        }
        //next - access to next middleware
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            try
            {
                await next.Invoke(context); // here we call next middleware?
            }
            catch(Exception e)
            {
                context.Response.StatusCode = 500;
                await context.Response.WriteAsync("Something went wrong");
            }
        }
    }
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,StudentSeeder seeder)
        {

            seeder.Seed();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyLibrus v1"));
            }
            //start of request

            app.UseMiddleware<ErrorHandlingMiddleware>();

            app.UseAuthentication();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

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

public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<ErrorHandlingMiddleware>();
...

有人可以告诉我为什么它不起作用?我的大摇大摆没有错误,但在 vs...

C# asp.net 错误处理 中间件

评论

0赞 ekke 7/16/2021
错误处理中间件应首先位于管道中,以确保捕获所有错误,因此请将其移至 configure 函数的顶部。其次,如果您在调试模式下运行,那么开发人员异常页面可能会捕获它。
0赞 ruddnisrus 7/17/2021
@ekke 你知道怎么解决吗?

答: 暂无答案