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, butviewName
comes through asnull
, 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 asnull
- 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?