| | | 1 | | using Microsoft.AspNetCore.Mvc.Filters; |
| | | 2 | | |
| | | 3 | | namespace OzonOrdersWeb.Observability; |
| | | 4 | | |
| | 0 | 5 | | public sealed class InvalidModelStatePageFilter(ILogger<InvalidModelStatePageFilter> logger) : IAsyncPageFilter |
| | | 6 | | { |
| | 0 | 7 | | public Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context) => Task.CompletedTask; |
| | | 8 | | |
| | | 9 | | public async Task OnPageHandlerExecutionAsync( |
| | | 10 | | PageHandlerExecutingContext context, |
| | | 11 | | PageHandlerExecutionDelegate next) |
| | | 12 | | { |
| | 0 | 13 | | if (!context.ModelState.IsValid) |
| | | 14 | | { |
| | 0 | 15 | | var errors = context.ModelState |
| | 0 | 16 | | .Where(pair => pair.Value is { Errors.Count: > 0 }) |
| | 0 | 17 | | .ToDictionary( |
| | 0 | 18 | | pair => pair.Key, |
| | 0 | 19 | | pair => pair.Value!.Errors.Select(error => |
| | 0 | 20 | | string.IsNullOrWhiteSpace(error.ErrorMessage) |
| | 0 | 21 | | ? error.Exception?.GetType().Name ?? "ValidationError" |
| | 0 | 22 | | : error.ErrorMessage).ToArray()); |
| | | 23 | | |
| | 0 | 24 | | var summary = string.Join("; ", errors.Take(3).Select(e => $"{e.Key}: {string.Join(", ", e.Value)}")); |
| | 0 | 25 | | if (errors.Count > 3) |
| | | 26 | | { |
| | 0 | 27 | | summary += $" (+{errors.Count - 3} ещё)"; |
| | | 28 | | } |
| | | 29 | | |
| | 0 | 30 | | using var scope = logger.BeginScope(new Dictionary<string, object?> |
| | 0 | 31 | | { |
| | 0 | 32 | | ["EventKind"] = "FormValidationFailed", |
| | 0 | 33 | | ["EventCategory"] = "forms", |
| | 0 | 34 | | ["RequestPath"] = context.HttpContext.Request.Path.Value, |
| | 0 | 35 | | ["HttpMethod"] = context.HttpContext.Request.Method, |
| | 0 | 36 | | ["Page"] = context.ActionDescriptor.DisplayName, |
| | 0 | 37 | | ["TraceId"] = context.HttpContext.TraceIdentifier, |
| | 0 | 38 | | ["ValidationErrors"] = errors |
| | 0 | 39 | | }); |
| | 0 | 40 | | logger.LogWarning("Razor Page форма {Method} {Path} не прошла серверную валидацию: {ValidationSummary}", |
| | 0 | 41 | | context.HttpContext.Request.Method, context.HttpContext.Request.Path, summary); |
| | | 42 | | } |
| | | 43 | | |
| | 0 | 44 | | await next(); |
| | 0 | 45 | | } |
| | | 46 | | } |