验证ASP.NET Web API中的可选参数

时间:2012-10-31 12:15:49

标签: asp.net validation asp.net-web-api model-binding

如何在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; }
}

2 个答案:

答案 0 :(得分:0)

听起来你想要添加约束。约束记录为here,用于确保路径中有有效输入。如果违反约束,则其控制器/操作不匹配,因此不会被调用。约束可以是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+"
        }
);

答案 1 :(得分:0)

只需将模型验证添加到您的方法或控制器,您就可以自动获得所需内容:

[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."]}}

阅读complete story about model validation

相关问题