Spaces:
Runtime error
Runtime error
almakhmri253-stack
security hardening: rate limiting, account lockout, security headers, password strength
8a2f194 Download Middleware/ExceptionMiddleware.cs from azizproject/majlis: direct link, hf CLI and curl.
- Browser
- Download file 1.83 kB
-
https://huggingface.co/spaces/azizproject/majlis/resolve/main/Middleware/ExceptionMiddleware.cs
- Command line
-
hf download hf://spaces/azizproject/majlis/Middleware/ExceptionMiddleware.cs
-
curl -L -o ExceptionMiddleware.cs https://huggingface.co/spaces/azizproject/majlis/resolve/main/Middleware/ExceptionMiddleware.cs
1.83 kB
| using System.Net; | |
| using System.Text.Json; | |
| namespace MajlisManagement.Middleware; | |
| public class ExceptionMiddleware | |
| { | |
| private readonly RequestDelegate _next; | |
| private readonly ILogger<ExceptionMiddleware> _logger; | |
| public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger) | |
| { | |
| _next = next; | |
| _logger = logger; | |
| } | |
| public async Task InvokeAsync(HttpContext context) | |
| { | |
| try | |
| { | |
| await _next(context); | |
| } | |
| catch (Exception ex) | |
| { | |
| _logger.LogError(ex, "Unhandled exception"); | |
| await HandleExceptionAsync(context, ex); | |
| } | |
| } | |
| private static async Task HandleExceptionAsync(HttpContext context, Exception ex) | |
| { | |
| context.Response.ContentType = "application/json"; | |
| var (statusCode, message) = ex switch | |
| { | |
| KeyNotFoundException => (HttpStatusCode.NotFound, ex.Message), | |
| InvalidOperationException => (HttpStatusCode.BadRequest, ex.Message), | |
| UnauthorizedAccessException => (HttpStatusCode.Unauthorized, ex.Message), | |
| InvalidDataException => (HttpStatusCode.BadRequest, ex.Message), | |
| // لا تكشف تفاصيل الأخطاء الداخلية للمستخدم | |
| _ => (HttpStatusCode.InternalServerError, "حدث خطأ داخلي، يرجى المحاولة لاحقاً") | |
| }; | |
| context.Response.StatusCode = (int)statusCode; | |
| await context.Response.WriteAsync(JsonSerializer.Serialize(new | |
| { | |
| success = false, | |
| message, | |
| statusCode = (int)statusCode | |
| }, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })); | |
| } | |
| } | |