【问题标题】:How to catch web api uri parameters binding errors?如何捕获 web api uri 参数绑定错误?
【发布时间】:2013-09-08 15:31:42
【问题描述】:

我正在使用 asp.net web-api 并试图捕捉 2 种情况:

  1. 传递了未定义的 Uri 参数
  2. 传递的 Uri 参数值无效

参数和值绑定成功,但是当名称或值无效时,不会发生异常并传递一个空值。

更多细节:
ModelState.IsValid 始终为真
我已清除所有格式化程序 使用GlobalConfiguration.Configuration.Formatters.Clear(); 然后添加我继承的 XmlMediaTypeFormatter 设置XmlSerializer = true
此外,我正在为复杂类型使用模式生成类(xsd 工具)

这是控制器方法签名:

public Messages GetMessages(int? startId = null, int? endId = null, DateTime? startDate = null, DateTime? endDate = null, int? messageType = null, string clientId = "", bool isCommentsIncluded = false)

有什么想法吗?

【问题讨论】:

    标签: c# asp.net-web-api


    【解决方案1】:

    创建一个类并装饰您希望验证的属性。例如(显然,使用你自己的值)

    public class ModelViewModel
    {
        public int Id { get; set; }
        [Required]
        public int RelationshipId { get; set; }
        [Required]
        public string ModelName { get; set; }
        [Required]
        public string ModelAttribute { get;set; }
    }
    

    创建一个过滤器,因此您不必在每个控制器中都使用 Model.IsValid。

    public class ValidationFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var modelState = actionContext.ModelState;
    
            if (!modelState.IsValid)
                actionContext.Response = actionContext.Request
                     .CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
        }
    }
    

    最后将以下内容添加到 Global.asax 中的 Application_Start()

    GlobalConfiguration.Configuration.Filters.Add(new ValidationFilter());
    

    希望这会有所帮助。

    更新

    public Messages GetMessages([FromUri] ModelViewModel model)
    

    您的模型类现在将绑定到 uri checkout this question 中的值

    【讨论】:

    • 谢谢,但我不确定我是否理解您的解决方案如何将它用于通过 Uri 传递的简单类型,使用这个单一类而不是简单类型?
    • 我不知道我的代码发生了什么变化,但我现在可以正确更新 ModelState.IsValid。正如您所建议的,很高兴了解另一种执行此操作的选项,但它不适用于检测任何拼写错误的参数
    猜你喜欢
    • 2017-11-19
    • 2018-05-08
    • 1970-01-01
    • 2014-09-10
    • 2013-12-04
    • 2017-02-03
    • 1970-01-01
    • 2017-01-24
    • 2014-05-11
    相关资源
    最近更新 更多