9

I created a ASP.net Web API controller like that:

public class UsersController : ApiController
{
    //...
    public void Put([FromBody]User_API user, long UpdateTicks)
    {
        user.UpdateTicks = UpdateTicks;
        //...
    }
}

The "user" parameter will be null if the client does not provide correct arguments. Can I make a global filter to check every parameter like this, and will return a 400 message if any error occurs.

guogangj
  • 2,275
  • 3
  • 27
  • 44
  • check out this http://stackoverflow.com/questions/11686690/handling-modelstate-validation-with-asp-net-web-api/11724405#11724405 – cuongle Jan 25 '13 at 07:23

1 Answers1

11

Finally, I got the solution:

public class ModelValidateFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ActionArguments.Any(v => v.Value==null))
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }
}

And...

//In Application_Start()
GlobalConfiguration.Configuration.Filters.Add(new ModelValidateFilterAttribute());
guogangj
  • 2,275
  • 3
  • 27
  • 44
  • This solution will work fine when your action does not use the FromUri parameter attribute. I have found that if you use (for example): `FromUri (Name="request")` and your parameter name is myRequest, then the expected ActionArguments will be null - returning a BadResponse. I have not found a clean way around this yet. – dubs Mar 29 '16 at 08:09
  • @dubs could you do a for each and type check on object? `argument.GetType().IsClass` – Thomas Jun 07 '16 at 16:44