Adding tests for ValidationActionFilter

This commit is contained in:
2025-06-19 23:14:43 +02:00
parent 2d7db3d919
commit e1d1381a5c
3 changed files with 161 additions and 3 deletions

View File

@@ -1,3 +1,4 @@
using BasicDotnetTemplate.MainProject.Models.Api.Base;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Threading.Tasks;
@@ -12,15 +13,27 @@ namespace BasicDotnetTemplate.MainProject.Core.Filters
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(new { message = _requestNotWellFormedMessage, errors = context.ModelState });
context.Result = new BadRequestObjectResult(new ValidationError
{
Message = _requestNotWellFormedMessage,
Errors = context.ModelState.Where(m =>
m.Value != null && m.Value.Errors.Any())
.ToDictionary(
m => m.Key,
m => m.Value!.Errors.Select(e => e.ErrorMessage).ToList()
)
});
return;
}
var requestBody = context.ActionArguments.Values.FirstOrDefault(arg => arg != null && !arg.GetType().IsPrimitive && !(arg is string));
var requestBody = context.ActionArguments.Values.FirstOrDefault(arg => arg != null && !arg.GetType().IsPrimitive && arg is not string);
if (requestBody == null)
{
context.Result = new BadRequestObjectResult(new { message = _requestNotWellFormedMessage });
context.Result = new BadRequestObjectResult(new ValidationError
{
Message = _requestNotWellFormedMessage
});
return;
}

View File

@@ -0,0 +1,9 @@
using System;
namespace BasicDotnetTemplate.MainProject.Models.Api.Base;
public class ValidationError
{
public string Message { get; set; }
public Dictionary<string, List<string>> Errors { get; set; }
}