ASP.NET Core 内置异常中间件的三种方法

发布时间 2023-12-28 12:17:47作者: leafroc

方法一

app.UseExceptionHandler(configure =>{
    configure.Run(async context => {
        var excHandler = context.Features.Get<IExceptionHandlerPathFeature>();
        var ex = excHandler.Error;
        if(ex != null)
        {
            context.Response.ContentType = "text/plain;charset=utf-8";
            await context.Response.WriteAsync(ex.ToString());
        }
    });
});

方法二

app.UseExceptionHandler(new ExceptionHandlerOptions(){
    ExceptionHandler = async context =>{
        var handler = context.Features.Get<IExceptionHandlerPathFeature>();
        var ex = handler.Error;
        if(ex != null)
        {
            context.Response.ContentType = "text/plain;charset=utf-8";
            await context.Response.WriteAsync(ex.ToString());
        }
    }
});

方法三

app.UseExceptionHandler(new ExceptionHandlerOptions{
    ExceptionHandlingPath = new PathString("/error")
});
app.Map("/error", () =>{
    return "error";
});