Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required attribute on action parameter doesn't work

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
}
like image 927
Json Avatar asked Aug 04 '26 14:08

Json


2 Answers

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.

like image 100
Mark Vincze Avatar answered Aug 07 '26 21:08

Mark Vincze


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

like image 34
oleksa Avatar answered Aug 07 '26 19:08

oleksa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!