【问题标题】:Mandatory and valid parameter in WebAPI requestWebAPI 请求中的强制和有效参数
【发布时间】:2012-06-07 06:58:34
【问题描述】:

我能否以某种方式将我的“输入对象”中的属性标记为强制执行且必须有效。 IE。如果我有:

public class MyInput
{
  //[SuperNeeded]
  public int FooBar { get; set; }
  public string Other { get; set; }
}

当请求没有 FooBar 或 FooBar 不是数字时,我想 ASP.NET 堆栈抛出异常。这些是有效的:

FooBar=1&Other=abc
FooBar=3

但这些不是(不希望 FooBar 为 0):

FooBar=abc&Other=abc //FooBar is not number
Other=abc //FooBar is missing

任何想法如何轻松做到这一点?

【问题讨论】:

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


    【解决方案1】:

    您是否尝试过使用RequiredAttribute

    【讨论】:

    • 是的,但这不符合我的要求。 FooBar 则简单地为 0(默认值(int))。我不能说它是 FooBar=0 还是缺失值。
    【解决方案2】:

    在这种情况下,你会想要:

    [Required]
    public int? FooBar { get; set; }
    

    这样你就不会简单地得到 0,如果它丢失,你会得到 null,如果传入 0,你会得到 0。

    【讨论】:

      猜你喜欢
      • 2012-09-10
      • 2016-09-06
      • 1970-01-01
      • 2023-03-27
      • 2019-04-29
      • 2022-08-19
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多