Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách Xử Lý Lỗi Trong Middleware C# ASP.NET Core


Tạo thư mục mới tên CustomExceptionMiddleware và lớp ExceptionMiddleware.cs bên trong.

Điều đầu tiên cần làm là đăng ký dịch vụ IloggerManager và RequestDelegate qua dependency injection.

Tham số _next kiểu RequestDelegate là một delegate hàm có thể xử lý các yêu cầu HTTP của chúng ta.

Sau quá trình đăng ký, chúng ta cần tạo phương thức InvokeAsync(). RequestDelegate không thể xử lý yêu cầu nếu không có nó.

Delegate _next nên xử lý yêu cầu và hành động Get từ controller của chúng ta nên tạo phản hồi thành công. Nhưng nếu yêu cầu không thành công (và đúng là vậy, vì chúng ta đang ép buộc exception),

middleware của chúng ta sẽ kích hoạt khối catch và gọi phương thức HandleExceptionAsync.

public class ExceptionMiddleware{ 
    private readonly RequestDelegate _next; 
    private readonly ILoggerManager _logger; 
    public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger){ 
        _logger = logger; 
        _next = next; 
    } 
    public async Task InvokeAsync(HttpContext httpContext){ 
        try{ 
            await _next(httpContext); 
        } 
        catch (Exception ex){ 
            _logger.LogError($"Something went wrong: {ex}"); 
            await HandleExceptionAsync(httpContext, ex); 
        } 
    } 
    private Task HandleExceptionAsync(HttpContext context, Exception exception){ 
        context.Response.ContentType = "application/json"; 
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; 
        return context.Response.WriteAsync(new ErrorDetails(){ 
            StatusCode = context.Response.StatusCode, 
            Message = "Internal Server Error from the custom middleware." 
        }.ToString()); 
    } 
}

Sửa đổi lớp ExceptionMiddlewareExtensions với phương thức static khác −

public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app){ 
    app.UseMiddleware<ExceptionMiddleware>(); 
}

Sử dụng phương thức này trong phương thức Configure trong lớp Startup −

app.ConfigureCustomExceptionMiddleware();