Required attribute on action parameter doesn't work

◇◆丶佛笑我妖孽 提交于 2019-12-05 23:08:58

I've run into the same problem and solved it by implementing a custom action filter attribute evaluating all the validation attributes of the action method parameters.

I described the approach in this blog post, where I use ASP.NET Core 1.0, but the same approach should work with ASP.NET 4 as well.

here is @MarkVincze's answer adjusted for asp.net web

public class ValidateModelStateAttribute : System.Web.Http.Filters.ActionFilterAttribute 
// there are two ActionFilterAttribute, one for MVC and another one for REST
{
    /// <summary>
    /// Called before the action method is invoked
    /// </summary>
    /// <param name="context"></param>
    public override void OnActionExecuting(HttpActionContext context)
    {
        var parameters = context.ActionDescriptor.GetParameters();
        foreach (var p in parameters)
        {
            if (context.ActionArguments.ContainsKey(p.ParameterName))
                Validate(p, context.ActionArguments[p.ParameterName], context.ModelState);
        }

        if (!context.ModelState.IsValid)
        {
            context.Response = context.Request.CreateResponse(
                HttpStatusCode.BadRequest,
                context.ModelState.Select(_ => new { Parameter = _.Key, Errors = _.Value.Errors.Select(e => e.ErrorMessage ?? e.Exception.Message) }),
                context.ControllerContext.Configuration.Formatters.JsonFormatter
            ); 
        }
    }

    private void Validate(HttpParameterDescriptor p, object argument, ModelStateDictionary modelState)
    {
        var attributes = p.GetCustomAttributes<ValidationAttribute>();
        foreach (var attr in attributes)
        {
            if (!attr.IsValid(argument))
                modelState.AddModelError(p.ParameterName, attr.FormatErrorMessage(p.ParameterName));
        }
    }
}

In WebAPI, an action parameter will never be null. It is always instantiated by the framework. So you would rather use the Required attribute on the properties of your view model if you want to ensure that they are present.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!