How do you require certain properties from the URI of the request?

时间:2015-09-01 21:52:35

标签: asp.net asp.net-web-api asp.net-web-api2

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);
}

1 个答案:

答案 0 :(得分:0)

您检查过RouteTable吗?如果您告诉路由表您的“id”参数在默认路由中是可选的,则可能会发生这种情况。