Код: Выделить всё
ValidationFilterКод: Выделить всё
using Contracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Middleware.Filters
{
public class ValidationFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.ModelState.IsValid)
{
#pragma warning disable CS8602 // Dereference of a possibly null reference.
var errorsInModelState = context.ModelState
.Where(o => o.Value.Errors.Count > 0)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Errors.Select(o => o.ErrorMessage)).ToArray();
#pragma warning restore CS8602 // Dereference of a possibly null reference.
var errorResponse = new ErrorResponse();
foreach(var error in errorsInModelState)
{
foreach(var subError in error.Value)
{
var errorModel = new ErrorModel
{
FieldName = error.Key,
Message = subError
};
errorResponse.Errors.Add(errorModel);
}
}
context.Result = new BadRequestObjectResult(errorResponse);
return;
}
await next();
}
}
}
Код: Выделить всё
using Contracts;
using FluentValidation;
namespace Middleware.Validators
{
public class AddressingDtoValidator : AbstractValidator
{
public AddressingDtoValidator()
{
RuleFor(x => x.District)
.NotNull()
.NotEmpty()
.Matches("^[a-zA-Z0-9 ]*$");
RuleFor(x => x.Mr)
.NotNull()
.NotEmpty()
.Matches("^[a-zA-Z0-9 ]*$");
RuleFor(x => x.Quarter)
.NotNull()
.NotEmpty()
.Matches("^[a-zA-Z0-9 ]*$");
RuleFor(x => x.Street)
.NotNull()
.NotEmpty()
.Matches("^[a-zA-Z0-9 ]*$");
RuleFor(x => x.Building)
.NotNull()
.NotEmpty()
.Matches("^[a-zA-Z0-9 ]*$");
RuleFor(x => x.Corpus)
.NotNull()
.NotEmpty()
.Matches("^[a-zA-Z0-9 ]*$");
RuleFor(x => x.Building)
.NotNull()
.NotEmpty()
.Matches("^[a-zA-Z0-9 ]*$");
RuleFor(x => x.InstitutionName)
.NotNull()
.NotEmpty()
.Matches("^[a-zA-Z0-9 ]*$");
}
}
}
Код: Выделить всё
ErrorModelКод: Выделить всё
namespace Contracts.ViewModels
{
public class ErrorModel
{
public string? FieldName { get; set; }
public string? Message { get; set; }
}
}
Код: Выделить всё
ErrorResponseКод: Выделить всё
namespace Contracts.ViewModels
{
public class ErrorResponse
{
public List Errors { get; set; } = new List();
}
}
Код: Выделить всё
{
"errors": [
{
"fieldname": "....",
"message": "...."
}
]
}
Код: Выделить всё
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-b9157268dc1f793004182694c1acf1a7-67fd063ebec5cbc3-00",
"errors": {
"Quarter": [
"'Quarter' must not be empty."
]
}
}
Есть также Класс Program.cs, куда я добавляю этот валидатор в конвейер:
Код: Выделить всё
builder.Services.AddControllers(options =>
{
options.Filters.Add();
})
.AddFluentValidation(configuration => configuration.RegisterValidatorsFromAssemblyContaining());
Подробнее здесь: https://stackoverflow.com/questions/730 ... re-web-api
Мобильная версия