我正在尝试将 JSON 数据发布到 Web Api 方法,但 JSON 数据未绑定(bind)到模型。
这是我的模型:
[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; }
}
这是我的 Web Api 操作:
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;
}
}
在我添加[ModelBinder]之前,registerDataModel为空。添加[ModelBinder]后,registerDataModel是一个RegisterDataModel实例,但所有属性值为null。
这是我通过 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"
}
为了将我的发布数据绑定(bind)到 RegisterDataModel 属性,我缺少什么?感谢您的帮助。
最佳答案
与OP的问题无关,但与问题的标题相关
当我使用(公共(public))字段而不是属性时,我来到了这里
在 Model 类中(即没有 {get; set;}
)。
结果发现这也会导致绑定(bind)失败。
也许可以帮助某人。
关于asp.net-mvc-4 - ASP.Net Web Api 未在 POST 上绑定(bind)模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12761602/