Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Asp.net Web Api。向控制器发布复杂模型,收到的模型不正确_C#_Asp.net Mvc_Web_Asp.net Web Api - Fatal编程技术网

C# Asp.net Web Api。向控制器发布复杂模型,收到的模型不正确

C# Asp.net Web Api。向控制器发布复杂模型,收到的模型不正确,c#,asp.net-mvc,web,asp.net-web-api,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

我在将复杂的模型对象从客户端发布到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

您尝试过类似的方法吗。。。你有没有试过用邮递员这样的工具来写这篇文章?(确保您没有发送空的尸体)

[HttpPost]
[响应类型(类型(信用))]
公共异步任务发布([FromBody]PaymentModel payment)
{
尝试
{
如果(payment==null | | payment.Crediter==null)返回BadRequest();
var响应=新信用
{
BankInformationId=payment.Crediter.BankInformationId
};
返回Ok(响应);
}
捕获(例外情况除外)
{
返回InternalServerError(ex);
}
}

您是否使用默认型号活页夹?如果是,请尝试为您的复杂模型创建一个自定义模型。检查请求,查看从客户端发送的表单数据或json是否与您的强类型类一致
PaymentModel
我可以拥有模型对象,但问题是我无法将Crediter转换为EmployeeCrediter。您是说,在收到的模型中,键入前,您有一个有效的
参数Crediter.BankInformationId值吗?事实上,我认为这个问题看起来像是接口的模型活页夹。在这种情况下,默认活页夹无法处理,您的答案不正确。是否要使用。。。像你想用的东西。。。类似var resp=wait this.Request.Content.ReadAsStringAsync()的内容;var payment=Newtonsoft.Json.JsonConvert.DeserializeObject(resp);
[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);
            }
        }