如何驗證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
沒有驗證錯誤,count只是變爲null。
有沒有辦法檢測到這個並返回錯誤信息?我想我記得在自定義消息處理程序的某個地方看到了一個解決方案,但是我再也找不到它了。
控制器方法是這樣的:
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; }
}