Is routing and validation of web API attributes possible?

I am trying to combine attribute-based routing in a web API with model validation. I just can't get it to work as I expected.

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 somethingchecked correctly, I have some problems:

  • When I specify only the value of the parameter somethingthat comes through OK, but viewNamepasses through null, and yet the state of the model is valid - I would expect a default value, since nothing was specified
  • When I specify an empty parameter viewName( ?something=x&viewName=), it comes as "DefaultView", and the state of the model is valid - I would expect it as an empty string as indicated
  • If I delete [FromUri], requestsequentially runs asnull
  • , (.. id , ), , ,

, , . , MVC, -API , - ASP.NET. !

, ? DefaultValueAttribute , ? - - , ?

+3

All Articles