user9393635
user9393635

Reputation: 1429

how can I validate this invalid property in web api?

I have a user search request object which looks like this:

UserSearchRequest
{
    FirstName:"John",
    LastName:"Smith",
    Expand:["groups","devices"]
}

Expand is an optional parameter. I have validation which checks that the provided Expand parameters are within thin expected set of parameters. The problem is that if a client submits a request like this:

{
    FirstName:"John",
    LastName:"Smith",
    Expand:1
}

By default Web API 2 will pass this request to the controller method with an Expand value of null. So the user won't know that he submitted a bad request and the controller won't be able to identify it as a bad request b/c null is a valid value for this property. Is there a way to override this default behavior?

Upvotes: 0

Views: 410

Answers (1)

Tej
Tej

Reputation: 414

Action Filters are triggered before controller executes its logic. I will give a general idea of what you need to do to get you on the right track.

First requirement for an Action Filter is to create your own filter class by extending ActionFilterAttribute class.

The following is a sample for this

public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            //Write your logic to check that all attributes are not null
        }
    }

Now onto the second step. This step will register your filter in WebApiConfig class so that the application will know that it has to pass requests to this filter wherever the attribute is used:

config.Filters.Add(new ValidateModelAttribute());

Now the third step is to call the custom class as an attribute on the controller method that is being executed when user makes a request:

[ValidateModel]

Hope this helps you to customise it for your own logic. Happy coding.

Upvotes: 2

Related Questions