2

我正在尝试调用 POST API 控制器。控制器被调用,但复杂对象为空。我已经运行了 Fiddler,并且该对象甚至来自那里。我究竟做错了什么?

我的 C# 对象

public class RegisterUser
{
    public Guid PersonId { get; set; }
    public string Email { get; set; }
    public string Business { get; set; }
    public string EmployeeNumber { get; set; }
    public string UserName { get; set; }
}

API 后控制器

public HttpResponseMessage Post(RegisterUser user)
{
   //This is where the problem is. Everything in user is null 
   //even though I can see it coming through on Fiddler.
}

Javascript代码

function User(personId, userName, email, business, employeeNumber) {
   this.PersonId = personId;
   this.Email = email;
   this.Business = business;
   this.EmployeeNumber = employeeNumber;
   this.UserName = userName;
}

function RegisterUser(url) {
   var createdUser = new User("b3fd25ba-49e8-4247-9f23-a6bb90a62691", "username", "email", "business", "56465");
   $.ajax(url, {
       data: JSON.stringify({ user: createdUser }),
       type: "post",
       contentType: "application/json"
  });
}

Web API 路由配置

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "RegisterApi",
            routeTemplate: "api/{controller}/{user}"
        );
    }
}
4

1 回答 1

3

createdUser已经以正确的格式包含 Web.Api 所需的数据,无需将其包装在user混淆模型绑定器的属性中。

只需编写data: JSON.stringify(createdUser)它应该可以正常工作:

function RegisterUser(url) {
   var createdUser = new User("b3fd25ba-49e8-4247-9f23-a6bb90a62691", "username", "email", "business", "56465");
   $.ajax(url, {
       data: JSON.stringify(createdUser),
       type: "post",
       contentType: "application/json"
  });
}

模型绑定的原理很简单,除非您在 JS 和 C# 对象中具有匹配的属性名称和对象结构,并且它应该可以正常工作。

于 2013-01-24T20:12:11.877 回答