簡體   English   中英

使用 C# 的 int?[] 屬性的數據注釋

[英]Data annotation for int?[] property using C#

我有一個 C# 屬性,如下所述:

public int?[] SubType { get; set; }

它是 forms 應用程序中 API 調用的參數之一。 很有可能在不為此參數設置任何值的情況下形成 API 調用,在這種情況下,應該為它分配 null 值,如下面的示例中所述:

HTTP POST 請求 object:

{
  "countries": [],
  "tagIds": [],
  "pattern": "abc",
  "limit": 5,
  "offset": 0
}

現在,如果有人為此參數提供了值,那么在這種情況下,我正在尋找以下要求:

  1. 最小值應為 1,最大值應為 9
  2. 沒有一個值應該是負數

例如:有效請求

{
    "countries":[],
    "tagIds":[],
    "pattern":"abc",
    "subType:[1,9], 
    "limit":5,
    "offset":0  
}

無效的請求:

{
    "countries":[],
    "tagIds":[],
    "pattern":"abc",
    "subType":[-1,100]  
    "limit":5,
    "offset":0  
}

誰能通過一些示例示例幫助我了解如何解決此問題?

我添加了一個自定義數據注釋並在 model class 級別使用,如下所述: // ValidateArticleSubTypeAttribute.cs

public sealed class ValidateArticleSubTypeAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object subType, ValidationContext validationContext)
    {
        // Since SubType is null, hence allow null
        int? [] arrSubType = subType as int? [];
        if (arrSubType == null || arrSubType.Length == 0)
        {
            return ValidationResult.Success;
        }

        // Validation for negative numbers
        bool allPositive = arrSubType.All(s => s > 0);
        if (!allPositive)
        {
            return new ValidationResult("Enter only positive values between 1 and 9");
        }

        // Validation for Min and Max value of the SubType array
        var min = arrSubType.Min();
        var max = arrSubType.Max();
        if (min < 1 || max > 9)
        {
            return new ValidationResult("Enter only positive values between 1 and 9");
        }

        return ValidationResult.Success;
    }
}

在 model class 處使用:

public class SampleSearchDTO
{
    [ValidateArticleSubType()]
    public int? [] SubType
    {
        get;
        set;
    }
}

這個解決方案對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM