【问题标题】:How do you require certain properties from the URI of the request?您如何从请求的 URI 中要求某些属性?
【发布时间】:2015-11-27 06:32:36
【问题描述】:

我有一个非常简单的模型:

public class FoobarGETRequestModel {
    [Required]
    public string Id { get; set; }
}

它被用于这样的绑定:

[HttpGet]
[ValidateModel] //This is a custom attribute for handling validation errors
public async Task<HttpResponseMessage> Foobar([FromUri]FoobarGETRequestModel model) {
    ...
}

如果我向/api/controller/foobar 发出请求(请注意,我没有提供Id 参数),ModelState.IsValid 属性始终返回 true(来自操作过滤器和上述方法)。

如何通过 URI 进行绑定并仍然利用框架 ModelState 验证?

编辑:这是ValidateModel 的样子:

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

【问题讨论】:

  • 所以你是说Id 属性没有被设置(即使在默认构造函数中?或者路由中的​​默认值?)并且模型状态仍然有效,尽管@987654330 @ 应该是 null?
  • @rdoubleui - 正确。其实从调试来看,model对象其实是null。
  • ValidateModel 长什么样子?
  • @rdoubleui - 我用ValidateModel 更新了我的帖子。如您所见,它非常简单;只需从ModelState 中获取错误并将它们放入对象中以进行响应。
  • 如果您说model 对象为空,那么还有一个问题需要先解决,不是吗?

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-07-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多