首页 > 解决方案 > 为什么错误处理中间件在asp中不起作用

问题描述

我的简单应用程序错误处理中间件有问题...当我篡改 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.neterror-handlingmiddleware

解决方案


推荐阅读