Files
Diary/Shared/ValidationFilter.cs
2022-09-02 22:22:51 +01:00

43 lines
1.2 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Diary.Shared
{
public class ValidationFilter : IAsyncActionFilter
{
public const string OverviewTitle = "The request is invalid.";
public const string OverviewMessage = "The request sent data that is not correct for the request.";
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (context.ModelState.IsValid)
{
await next();
}
else
{
ValidationExceptionDetails errorObj = new()
{
Title = OverviewTitle,
Message = OverviewMessage,
ModelState = GetErrors(context.ModelState)
};
context.Result = new BadRequestObjectResult(errorObj);
}
}
private static List<ValidationProblemDescriptor> GetErrors(ModelStateDictionary modelState)
{
List<ValidationProblemDescriptor> errors = new();
return modelState.Where(ms => ms.Value?.Errors.Count > 0)
.Select(x => new ValidationProblemDescriptor
{
Property = x.Key,
Errors = x.Value?.Errors.Select(e => e.ErrorMessage).ToArray()
})
.ToList();
}
}
}