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.

1

1 Answer 1

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());
Sign up to request clarification or add additional context in comments.

2 Comments

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 could you do a for each and type check on object? argument.GetType().IsClass

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.