This question is similar to what I want to achieve:
Avoiding null model in ASP.Net Web API when no posted properties match the model
But it's gone un-answered.
I have a route which takes a model that is a GET:
[HttpGet, Route("accounts")]
public AccountListResult Post(AccountListRequest loginRequest)
{
return accountService.GetAccounts(loginRequest);
}
The model is populated with additional data from an action filter.
In this case all that needs to be known is the UserId, which the action filter add's to the model based on cookie/header into passed in with the request.
I want to use all the default model binding in WebAPI but I want to avoid null objects.
I don't believe model binding solves my problem.
This is closer to what I want to do except its per type which is tedious.
EDIT: Since the question is for Web API, I am posting the Web API solution also below.
You can do this as below in an Action Filter. The below code works only if your model contains default constructor.
Web API Implementation:
MVC Implementation:
@Sarathy's solution works, but doesn't trigger model validation on objects it creates. This can cause situations where an empty model was passed in to an action but
ModelState.IsValid
still evaluates true.For my own purposes, it was necessary to trigger re-validation of the model in the event that an empty model object was created: