簡體   English   中英

ASP.NET 核心 WebAPI FromBody 屬性未驗證 object 非參考字段

[英]ASP.NET Core WebAPI FromBody attribute is not validating object non-reference fields

我在我的 controller 中有操作 Create:

[HttpPost]
public async Task<IActionResult> Create([FromBody] PostCreate createDto)
{
    // do something with Create DTO
}

它接受 DTO 來創建 Post(參數標有 [FromBody] 屬性)。 該 DTO 有 2 個屬性:字符串(引用類型)內容屬性和 System.Guid(值類型)屬性:

public class PostCreate
{
    [Required(ErrorMessage = "content is required")]
    public string Content { get; set; }

    [Required(ErrorMessage = "blog id is required")]
    public Guid BlogId { get; set; }
}

問題是,當我發送有效的 object 時,一切正常(Content 和 BlodId 屬性都已初始化)。 但是當我發送空的 object 時,它只檢查 Content 屬性:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|dfcd1687-4a0b9320d8411509.",
    "errors": {
        "Content": [
            "content is required"
        ]
    }
}

如果我只為 Content 屬性提供值,它將通過驗證,並且 BlogId 值為“00000000-0000-0000-0000-000000000000”或 Guid.Empty。 所有非引用類型都是一樣的(例如,int 值為 0)。

問題 1:“為什么它會這樣?” 問題 2:“如何使默認驗證檢查非引用類型的空虛?”

更新(有用的解決方法)

正如Octavio Armenta答案中指出的那樣:“您可能必須創建一個自定義屬性來檢查 Guid 的空性。如果您想使用屬性。”。 我是這樣做的:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class NotEmptyAttribute : ValidationAttribute
{
    public const string DefaultErrorMessage = "The {0} field must not be empty";

    public NotEmptyAttribute()
        : base(DefaultErrorMessage) { }

    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return true;
        }

        return value switch
        {
            Guid guid => guid != Guid.Empty,
            // other non-reference types checks
            _ => true
        };
    }
}

注意:上面的代碼片段使用了一個僅在 C# 8 之后才可用的switch 表達式。您也可以使用常規switch 語句

Guid 的默認值為Guid.Empty ,它通過了RequiredAttribute的驗證。 您可能必須創建一個自定義屬性來檢查 Guid 是否為空。 如果你想使用一個屬性。

值類型的屬性使用值類型的默認值進行初始化。 如果您將不可為空的類型更改為可空的(即GuidGuid? ),您的驗證應該按預期工作:

public class PostCreate
{
    [Required(ErrorMessage = "content is required")]
    public string Content { get; set; }

    [Required(ErrorMessage = "blog id is required")]
    public Guid? BlogId { get; set; }
}

Content已按預期進行驗證,因為字符串的默認值為null

暫無
暫無

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

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