【问题标题】:Is there something like [Bind(Exclude="Property")] for asp.net web api?asp.net web api有类似[Bind(Exclude="Property")]的东西吗?
【发布时间】:2015-05-08 06:32:30
【问题描述】:

我试图在 web api 控制器中从我的 Post Action 中排除一个属性,对于 asp.net web api 是否有类似 [Bind(Exclude="Property")] 的东西?

这是我的模型:

public class ItemModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

我想在 Post Action 中排除 Id,因为它是自动生成的,但我需要在 Get Action 中返回它。

我知道我可以有两个模型,一个用于我的 Post 操作,一个用于我的 Get 操作,但我正在尝试只使用一个模型。

【问题讨论】:

  • 可以将 Id 设置为可为空的 int
  • 当你忽略它(int)时,你期待什么真的很有趣。默认?无论如何都会有一些价值。请添加有关生成的更多详细信息

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


【解决方案1】:

我更喜欢映射模型,但这可以通过在 ShouldSerialize 方法中检查请求是否为 POST 来实现:

public class MyModel
{
    public string MyProperty1 { get; set; }
    public string MyProperty2 { get; set; }

    public bool ShouldSerializeMyProperty2()
    {
        var request = HttpContext.Current.Request;

        if (request.RequestType == "POST") return false;

        return true;
    }
}

您的方法名称是前缀为 ShouldSerialize 的属性名称。

请注意,这适用于 JSON。对于 XML,您需要将以下行添加到您的配置中:

config.Formatters.XmlFormatter.UseXmlSerializer = true; 

【讨论】:

    【解决方案2】:

    您可以简单地为 POST 创建一个 DTO。

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请编辑以添加更多详细信息,例如引用或文档或代码,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到更多关于如何写出好的答案的信息。
    猜你喜欢
    • 2017-07-15
    • 2014-09-22
    • 2010-11-29
    • 2020-03-26
    • 2011-10-18
    • 2023-03-09
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多