ASP.Net Web Api not binding model on POST

Tom Schreck picture Tom Schreck · Oct 6, 2012 · Viewed 21.9k times · Source

I'm trying to POST JSON data to a Web Api method but the JSON data is not binding to the model.

Here's my model:

[DataContract]
public class RegisterDataModel
{
    [DataMember(IsRequired = true)]
    public String SiteKey { get; set; }

    [DataMember(IsRequired = true)]
    public String UserId { get; set; }

    [DataMember(IsRequired = true)]
    public String UserName { get; set; }
}

Here's my Web Api action:

    public class RegisterController : ApiController
    {
    public Guid Post([ModelBinder] RegisterDataModel registerDataModel)
    {
        if (!ModelState.IsValid)
        {
            throw new ModelStateApiException(ModelState);
        }
        var userProfileDataContract = userProfileBusinessLibrary.GetNewOne();
        userProfileDataContract.UserId = registerDataModel.UserId;
        userProfileDataContract.UserName = registerDataModel.UserName;

        var userKey = userProfileBusinessLibrary.Register(registerDataModel.SiteKey, userProfileDataContract);

        return userKey;
    }
    }

Before I added [ModelBinder], registerDataModel was null. After adding [ModelBinder], registerDataModel is a RegisterDataModel instance, but all of the property values are null.

Here's my Request via Fiddler:

http://local.testwebsite.com/api/register

Request Headers:
User-Agent: Fiddler
Host: local.testwebsite.com
Content-Length: 89
Content-Type: application/json; charset=utf-8:

Request Body:
{ 
 "SiteKey":"qwerty",
 "UserId": "12345qwerty", 
 "UserName":"john q"
}    

What am I missing to make my post data bind to the RegisterDataModel properties? Thanks for your help.

Answer

robert4 picture robert4 · Jan 17, 2014

Not related to the OP's problem, but the title of the question led me here when I used (public) fields instead of properties in the Model class (i.e. no {get; set;}). It turned out that this also causes the binding to fail.

Maybe helps someone.