I have a very simple model:
public class FoobarGETRequestModel {
[Required]
public string Id { get; set; }
}
It's being used for binding like so:
[HttpGet]
[ValidateModel] //This is a custom attribute for handling validation errors
public async Task<HttpResponseMessage> Foobar([FromUri]FoobarGETRequestModel model) {
...
}
If I make a request to /api/controller/foobar
(notice I'm not providing an Id
parameter), the ModelState.IsValid
property always returns true (from both an action filter and from within the method above).
How do I bind via the URI and still leverage the frameworks ModelState
validation?
Edit: Here is what ValidateModel
looks like:
if (actionContext.ModelState.IsValid == false) {
var responseObject = new FooApiExceptionResponse() {
Errors = actionContext.ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)
};
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, responseObject);
}
答案 0 :(得分:0)
您检查过RouteTable吗?如果您告诉路由表您的“id”参数在默认路由中是可选的,则可能会发生这种情况。