Asp.net Web Api。将复杂模型发布到Controller并且接收模型不正确

时间:2016-12-28 08:08:28

标签: c# asp.net-mvc web asp.net-web-api

我遇到了从客户端到Web Api控制器发布复杂模型对象的问题。 我的模型结构是:

public class PaymentModel
{
    public Credit Crediter { get; set; }
}

public class Credit : ICredit
{
    public int BankInformationId { get; set; }
}

public interface ICredit
{
    int BankInformationId { get; set; }
}

public sealed class CrediterEmployee:Credit
{
    public int EnployeeId { get; set; }
}

我尝试创建一个模型以发布到API控制器:

var param = new PaymentModel
{
    Crediter = new CrediterEmployee
    {
        BankInformationId = 4928,
        EnployeeId = 7013
    },
}

在API控制器中,我收到了一个模型对象,但对于Crediter,我无法转换为CreditEmployee。当我试图施展时,它是null

如何将Crediter投射到CreditEmployee

1 个答案:

答案 0 :(得分:0)

你尝试过这样的事吗? ...你有没有尝试过像POSTMAN这样的工具? (确保你不发送空身)

[HttpPost]
[ResponseType(typeof(Credit))]
public async Task<IHttpActionResult> Post([FromBody] PaymentModel payment)
        {
            try
            {
                if (payment == null || payment.Crediter == null) return BadRequest();
                var response = new Credit
                {
                    BankInformationId = payment.Crediter.BankInformationId
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }