簡體   English   中英

如何檢查 DTO 是否在 .net 中具有預期的數據類型?

[英]how to check if DTO has the expected data types in .net?

我在 .net 中完成了一個 webapi。 我想驗證用戶插入的數據是否具有預期的數據類型。 這是我的 DTO:

    public class EditHash
{
    public EditHash()
    {
    }
    public string? UrlShort { get; set; }
    public string? UrlOrigin { get; set; }
    public DateTime ExpireAt { get; set; }
}

這是我嘗試驗證數據類型的方法:

        public async Task<IActionResult> ModifyUrl(string hash, [FromBody] Request.EditHash h )
    {
if(!(h.ExpireAt is DateTime) ||  !(h.UrlShort is string))
        {
            gc.errorNumber = "505";
            gc.value = "Bad Request";
            gc.detail = "One or many parameters data type are not correct";
            return new TimeoutExceptionObjectResult(error: gc, 400);
        }
    }

我也嘗試過這種方法:

if(h.ExpireAt.GetType()!=typeof(DateTime) || h.UrlOrigin.GetType()!=typeof(string) ||h.UrlShort.GetType()!= typeof(string))
        {
            ...
        }

在這兩種情況下,例如,當我插入 integer 而不是字符串時,代碼不會返回我定義的錯誤。 如何驗證數據類型?

如果您希望用戶可以使用“不正確”值調用您的 API(並獲得受控響應); 您需要一個更“寬松”的數據結構作為輸入,然后您可以檢查轉換為真實 DTO 的值:

public class EditHash_Permissive_Input
{
    public string UrlShort { get; set; }
    public string UrlOrigin { get; set; }
    public string ExpireAt { get; set; }
}

然后在暴露的方法中:

public async Task<IActionResult> ModifyUrl(string hash, [FromBody] Request.EditHash_Permissive_Input h )
{
if(!DateTime.TryParse(h.ExpireAt, out DateTime dateTimeInput) || String.IsNullOrEmpty(h.UrlShort)) //<- Add other desired validations to url as "1" is a string and could not be a valid url
    {
        gc.errorNumber = "505";
        gc.value = "Bad Request";
        gc.detail = "One or many parameters data type are not correct";
        return new TimeoutExceptionObjectResult(error: gc, 400);
    }
    else
    {
         Request.EditHash internalValue = new Request.EditHash() 
            {
                UrlShort = h.UrlShort,
                UrlOrigin = h.UrlOrigin,
                ExpireAt = dateTimeInput,
            }
         //Continue with what you mean to do with h data
    }
}

暫無
暫無

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

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