title: Web API model validation and default values
body: <p>This is the spiritual successor to my previous question <a href="https://stackoverflow.com/questions/30468805/web-api-attribute-routing-and-validation-possible">Web API attribute routing and validation - possible?</a>, which I think was too general to answer.  Most of those issues are solved, but the default value question remains.</p>
  
  <p>Basically I have solved many pieces of the puzzle.  I have this:</p>
  
  <pre><code>[HttpGet]
  [Route("test/{id}"]
  public IHttpActionResult RunTest([FromUri]TestRequest request)
  {
      if (!ModelState.IsValid) return BadRequest(ModelState);
      return Ok();
  }
  </code></pre>
  
  <p>My <code>TestRequest</code> class:</p>
  
  <pre><code>public class TestRequest
  {
      public string id { get; set; }
  
      [DefaultValue("SomethingDefault")]
      public string something { get; set; }
  }
  </code></pre>
  
  <p>The problem is that if no parameter is in the query string for <code>something</code>, the model is "valid" and yet <code>something</code> is <code>null</code>.</p>
  
  <p>If I specify a blank value for <code>something</code> (i.e. <code>GET test/123?something=</code>), then the default value comes into play, and the model is valid again.</p>
  
  <p>Why is this?  How can I get a default value into my model here?  As a bonus, why is it when a parameter is not specified, the default value is not used, but when a blank string is explicitly specific, the default value is used?</p>
  
  <p>(I've been trawling through the ASP.NET stack source code and am knee-deep in model binders and binding contexts.  But my best guess can't be right - it looks like the <code>DefaultValueAttribute</code> is used only if the parameter value is <code>null</code>.   But that's not the case here)</p>