Web API attribute routing and validation - possible?

偶尔善良 提交于 2019-12-10 17:42:34

问题


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?

来源:https://stackoverflow.com/questions/30468805/web-api-attribute-routing-and-validation-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!