【问题标题】:allow extra properties in webapi model在 webapi 模型中允许额外的属性
【发布时间】:2017-09-27 07:43:03
【问题描述】:

如何配置 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; }
}

谢谢

【问题讨论】:

  • 这个问题缺乏重要的背景。如果您期望得到好的答案,请花点时间写一个好问题。

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


【解决方案1】:

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

【讨论】:

  • 我添加了示例。收到后我们已经使用了automapper。问题是接收模型与客户端发送的模型不匹配。
【解决方案2】:

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

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; }
}

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

【讨论】:

    猜你喜欢
    • 2017-10-24
    • 2022-01-21
    • 2021-12-01
    • 2017-03-25
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    相关资源
    最近更新 更多