aspnetcore.3.0.validateModel.mustache Maven / Gradle / Ivy
{{>partial_header}}
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace {{packageName}}.Attributes
{
///
/// Model state validation attribute
///
public class ValidateModelStateAttribute : ActionFilterAttribute
{
///
/// Called before the action method is invoked
///
///
public override void OnActionExecuting(ActionExecutingContext context)
{
// Per https://blog.markvincze.com/how-to-validate-action-parameters-with-dataannotation-attributes/
if (context.ActionDescriptor is ControllerActionDescriptor descriptor)
{
foreach (var parameter in descriptor.MethodInfo.GetParameters())
{
object{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} args = null;
if ({{#nullableReferenceTypes}}parameter.Name != null && {{/nullableReferenceTypes}}context.ActionArguments.ContainsKey(parameter.Name))
{
args = context.ActionArguments[parameter.Name];
}
ValidateAttributes(parameter, args, context.ModelState);
}
}
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
}
private void ValidateAttributes(ParameterInfo parameter, object{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} args, ModelStateDictionary modelState)
{
foreach (var attributeData in parameter.CustomAttributes)
{
var attributeInstance = parameter.GetCustomAttribute(attributeData.AttributeType);
if (attributeInstance is ValidationAttribute validationAttribute)
{
var isValid = validationAttribute.IsValid(args);
if (!isValid{{#nullableReferenceTypes}} && parameter.Name != null{{/nullableReferenceTypes}})
{
modelState.AddModelError(parameter.Name, validationAttribute.FormatErrorMessage(parameter.Name));
}
}
}
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy