title: Validation for optional parameters in ASP.NET Web API
body: <p>How can I validate the data type of optional parameters in ASP.NET Web API?</p>
  
  <p>My routing looks like this:</p>
  
  <pre class="lang-csharp prettyprint-override"><code>context.MapHttpRoute(
      name: "ItemList",
      routeTemplate: "api/v1/projects/{projectId}/items",
      defaults: new
          {
              area = AreaName,
              controller = "Items",
              action = "GetItems",
              offset = RouteParameter.Optional,
              count = RouteParameter.Optional,
          }
  );
  </code></pre>
  
  <p>These would all be valid requests:  </p>
  
  <pre><code>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&amp;count=10
  </code></pre>
  
  <p>Everything works fine except when an invalid value is provided for one of the parameters. For example,</p>
  
  <pre><code>http://localhost/api/v1/projects/1/items?count=a
  </code></pre>
  
  <p>There is no validation error, count just becomes null.</p>
  
  <p>Is there a way to detect this and return an error message? I think I recall seeing a solution somewhere with custom message handlers but I cannot find it any more.</p>
  
  <p>The controller method looks like this:</p>
  
  <pre class="lang-c# prettyprint-override"><code>public IEnumerable&lt;Item&gt; GetItems([FromUri]GetItemsParams getItemsParams)
  {
      // logic
  }
  </code></pre>
  
  <p>And the params class looks like this:</p>
  
  <pre class="lang-c# prettyprint-override"><code>[DataContract]
  public class GetItemsParams
  {
      [DataMember] public int? offset { get; set; }
      [DataMember] public int? count { get; set; }
  }
  </code></pre>