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.

有帮助吗?

解决方案

How are you creating the JSON request? Through Fiddler request builder? Try just the following in the request body.

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

I'm guessing 'Request Body:' is also part of your request body. Remove that and check.

其他提示

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.

In my case, app's requests are passed through a middleware called "API Manager" for authentication / authorization before forwarding to my .NET Web API. POST parameter isn't binded because, for some reason I'm no idea why, the "Content-Length" is emitted from the Headers.The reason is because, the default JsonMediaTypeFormatter always check requests' Content-Length before doing model binding, and if the Content-Length is not presented it will set the parameter to NULL.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top