【问题标题】:Validation for optional parameters in ASP.NET Web API验证 ASP.NET Web API 中的可选参数
【发布时间】:2012-10-31 12:15:48
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    听起来您需要添加约束。约束记录在 here 中,用于确保您的路径中有有效的输入。如果违反了约束,就好像控制器/动作不匹配,因此不被调用。约束可以是正则表达式,如下例所示,也可以通过使用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+"
            }
    );
    

    【讨论】:

      【解决方案2】:

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

      [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

      【讨论】:

        猜你喜欢
        • 2012-04-04
        • 2023-04-08
        • 2018-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-08
        • 2021-08-11
        • 2017-08-30
        相关资源
        最近更新 更多