Web API参数绑定不起作用

时间:2014-12-25 05:25:23

标签: asp.net-web-api model-binding asp.net-web-api2

我有两个实体类DonorUser。捐赠者是用户的子类,如下所示

public abstract class User {
    [Key]
    public long Id { get; set; }
    ...
}    

public class Donor : User {
    public string AlternateMobileNumber { get; set; }
    ...
}

下面显示的web api控制器操作接收POST请求,其中包含正文中的JSON数据

public class DonorsController : ApiController  {

    //POST: api/Donors/EditDonor
    [HttpPost]
    public HttpResponseMessage EditDonor([FromBody] Donor donor) {
        ...
    }
}

以下是帖子请求的显示方式

POST http://localhost:xxxxx/Donor/api/Donors/EditDonor HTTP/1.1
Content-Length: 477
Cache-Control: no-cache
Content-Type: application/json;charset=UTF-8
Accept: */*
...

{"Id":12,"UserId":"donor9@abc.com","FirstName":"firstname9c","MiddleName":"M","LastName":"lastname9","Gender":"Male","MobileNumber":"7777777777","BloodGroup":"A+ve","OfficeLocality":{"Id":2,"Name":"Malad"},"ResidenceLocality":{"Id":2,"Name":"Malad"},"Organization":"organization9","Designation":"designation9","TimesDonated":1,"DateLastDonated":"Mon Dec 01 00:00:00 GMT+05:30 2014","LastDonatedAt":"Hosp 1","IsSDPDonor":false,"IsIntrestedDonor":false,"Comments":"Some Comment"}

问题是 Donor 对象为空(不为null但为空,没有将值应用于Donor的属性)。

如果我更改捐赠者对象并使用具有相同属性但没有任何继承的数据传输对象(DonorDO),则会在该Data对象中正确填充属性。例如,捐助者数据对象如下所示。

//Plain Data Transfer Object without inheritance
public class DonorDO {
    public long Id { get; set; }
    public string AlternateMobileNumber { get; set; }
    ...
}

为什么 DonorDO 正确绑定其属性值,而 Donor 实体对象保持为空,且没有绑定任何属性。它与继承还是其他一些问题有关。

1 个答案:

答案 0 :(得分:0)

我注意到你正在发帖到“http:// localhost:xxxxx / Donor / api / Donors / EditDonor”这是错误的,你需要POST到“http:// localhost:xxxxx / api / Donors “(你只需要POST到控制器基地址,控制器名称应该在”api“之后,而不是之前)。

此代码100%正常运行:

using System.Net;
using System.Net.Http;
using System.Web.Http;

//[Authorize]
public class DonorsController : ApiController
{

    [HttpGet]
    public Donor Get(int id)
    {
        return new Donor
        {
            Id = id,
            AlternateMobileNumber = "0000",
        };
    }

    //POST: api/Donors/EditDonor
    [HttpPost]
    public HttpResponseMessage EditDonor([FromBody] Donor donor)
    {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

public abstract class User
{
    public long Id { get; set; }
}

public class Donor : User
{
    public string AlternateMobileNumber { get; set; }
}

现在,使用fiddler我可以在下面的图像中看到这个方法,在控制器端你可以看到传递的供体参数。

Fiddler POST request/parameters

Visual Studio 2013 POST method Debug

希望这有帮助。