5

I'm trying to combine attribute-based routing in Web API with model validation. I simply can't get it to work as I would expect.

class MyRequestModel
{
    [DefaultValue("DefaultView")]
    public string viewName { get; set; }

    [Required]
    public string something { get; set; }
}

[HttpGet]
[Route("myroute/{id:minlength(2)}")]
public IHttpActionResult Test(string id, [FromUri]MyRequestModel request)
{
    if (!ModelState.IsValid) { return BadRequest(ModelState); }
    // process here...
    return Json( /* result */ );
}

Although something is validated correctly, I have some issues:

  • When I specify only a something parameter value, that comes through OK, but viewName comes through as null, and yet the model state is valid - I would expect the default value since nothing was specified
  • When I specify a blank viewName parameter (?something=x&viewName=), it comes through as "DefaultView", and the model state is valid - I would expect it as a blank string as specified
  • If I remove [FromUri], request comes through consistently as null
  • There seems to be no way to include route parameters as part of the model (i.e., id must be a parameter, not part of the request model), meaning - I think - that I can't use model state validation on routing parameters

I was validating parameters manually, but figured I would try to leverage the pre-built functionality and power of model state validation. I will admit however with the masses of overlapping and sometimes contradictory documentation around MVC, Web API and various versions thereof, I'm unable to find any single source of truth - just quick starter guides on the ASP.NET site. Pointers here would be very welcome, too!

Is it just not possible to combine these things in the way I'm expecting? Does DefaultValueAttribute not do what I think it does? Can I not validate all parameters to the controller somehow - including those appearing as a part of the routing?

Kieren Johnstone
  • 41,277
  • 16
  • 94
  • 144
  • See my more specific question here - http://stackoverflow.com/questions/30482415/web-api-model-validation-and-default-values - this question concerns routing and validation, which I have resolved. Just the default value issue remains! – Kieren Johnstone May 27 '15 at 12:27
  • Why don't you delete this question, that is in fact too complex to answer? Besides, IMO, you've got the right answer in your other question. – JotaBe May 27 '15 at 13:06

0 Answers0