Required attribute on action parameter doesn't work

寵の児 提交于 2019-12-07 15:06:38

问题


The code is like:

[HttpPost]
public ResultEntityVM Register([FromBody,Required] RegisterParam createAssessorParam)
{
    if (ModelState.IsValid == false)
    {
        return null;
    }

    //other code
    ResultEntityVM vm = new ResultEntityVM();
    return vm;
}

When the parameter createAssessorParam is null, the value of ModelState.IsValid is true. Why?

If I want to auto judge the parameter is null or not, what can I do? Don't I can only write the code:

if(RegisterParam  != null)
{
   //other
}

回答1:


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.




回答2:


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));
        }
    }
}




回答3:


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.



来源:https://stackoverflow.com/questions/31892333/required-attribute-on-action-parameter-doesnt-work

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