簡體   English   中英

驗證ASP.NET Web API中的可選參數

[英]Validation for optional parameters in ASP.NET Web API

如何驗證ASP.NET Web API中可選參數的數據類型?

我的路由如下所示:

context.MapHttpRoute(
    name: "ItemList",
    routeTemplate: "api/v1/projects/{projectId}/items",
    defaults: new
        {
            area = AreaName,
            controller = "Items",
            action = "GetItems",
            offset = RouteParameter.Optional,
            count = RouteParameter.Optional,
        }
);

這些都是有效的請求:

http://localhost/api/v1/projects/1/items  
http://localhost/api/v1/projects/1/items?offset=20  
http://localhost/api/v1/projects/1/items?count=10  
http://localhost/api/v1/projects/1/items?offset=20&count=10

一切正常,除非為其中一個參數提供了無效值。 例如,

http://localhost/api/v1/projects/1/items?count=a

沒有驗證錯誤,計數只是為空。

有沒有辦法檢測到此錯誤並返回錯誤消息? 我想我記得在某個地方使用自定義消息處理程序的解決方案,但是我再也找不到了。

控制器方法如下所示:

public IEnumerable<Item> GetItems([FromUri]GetItemsParams getItemsParams)
{
    // logic
}

params類如下所示:

[DataContract]
public class GetItemsParams
{
    [DataMember] public int? offset { get; set; }
    [DataMember] public int? count { get; set; }
}

聽起來您想添加約束。 約束記錄在此處 ,用於確保路徑中輸入的內容有效。 如果違反了約束,則控制器/動作將不匹配,因此不會被調用。 約束可以是RegEx,如下面的示例,也可以通過使用IRouteConstraint實現類來進行自定義

例如:

context.MapHttpRoute(
    name: "ItemList",
    routeTemplate: "api/v1/projects/{projectId}/items",
    defaults: new
        {
            area = AreaName,
            controller = "Items",
            action = "GetItems",
            offset = RouteParameter.Optional,
            count = RouteParameter.Optional,
        },
     constraints: new
        {
            offset = @"\d+",
            count = @"\d+"
        }
);

只需將模型驗證添加到您的方法或控制器中,您將自動獲得所需的內容:

[ValidateModel]
public IEnumerable<Item> GetItems([FromUri]GetItemsParams getItemsParams)
{
    // logic
}

現在當用

http://localhost/api/v1/projects/1/items?count=a

您會收到一條錯誤消息:

{"Message":"The request is invalid.","ModelState":{"getItemsParams.offset":["The value 'a' is not valid for offset."]}}

閱讀有關模型驗證完整故事

暫無
暫無

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

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