允许webapi模型中的额外属性

时间:2017-09-27 07:43:04

标签: c# .net asp.net-web-api serialization asp.net-web-api2

如何配置webapi以允许额外的属性,这些属性不在模型中且应该被忽略?目前序列化失败了它还有其他属性,但缺少(非必需)属性。我们需要这个来使api更加健壮。

webapi中的模型示例:

public class User
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}

但我们将此发送给合同:

public class User
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    public string IAmExtra  { get; set; }
}

由于

2 个答案:

答案 0 :(得分:0)

为什么不使用mapper从webapi Dtomodel映射到您的模型: / Using Automapper in ASP.NET Core project

答案 1 :(得分:0)

我们现在通过将模型类型设置为打开类型来解决这个问题:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/use-open-types-in-odata-v4

喜欢这个

public class User
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    public IDictionary<string, object> Properties { get; set; }
}

现在我们可以接受额外的属性,而不会出现序列化问题。

相关问题