【问题标题】:ModelState is coming false even when I've modified the property in action filter即使我修改了动作过滤器中的属性,ModelState 也会出现错误
【发布时间】:2014-10-08 16:52:56
【问题描述】:

我已在以下操作过滤器本身中修改了 ActionType,但仍然收到模型状态错误,因为“字段 ActionType 必须匹配正则表达式 '1|2|3|4'。”

对于我的模型属性为

[RegularExpression("1|2|3|4")]

public int ActionType { get; set; }

我的 ActionType 枚举是

 public enum ActionType
        {
            Add = 1,
            Update = 2,
            Delete = 3,
            Search = 4
        }

动作过滤器是

public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var formData = actionContext.ActionArguments.FirstOrDefault().Value as EntityBase;
            if (formData != null)
            {
                string methodType = actionContext.Request.Method.Method;
                switch (methodType.ToUpper())
                {
                    case "POST":
                        formData.ActionType = (int)ActionType.Add;
                        break;
                    case "PUT":
                        formData.ActionType = (int)ActionType.Update;
                        break;
                    case "DELETE":
                        formData.ActionType = (int)ActionType.Delete;
                        break;
                    case "GET":
                        formData.ActionType = (int)ActionType.Search;
                        break;
                    // Your errors
                }
            }
            base.OnActionExecuting(actionContext);
        }

【问题讨论】:

  • 模型绑定和验证发生在动作过滤器被触发
  • 嗨@Stephen 你能建议我在哪里做这个吗?
  • 您可以创建一个自定义模型绑定器来防止添加验证错误,或者(可能更容易,但我没有测试过)访问 actionContext.ModelState 属性并清除错误 - if (actionContext.ModelState.ContainsKey("ActionType")) { actionContext.ModelState["ActionType"].Errors.Clear(); } 但为什么如果您总是要在操作过滤器中设置它,请在属性上放置一个验证属性?
  • 哦,没错,我总是会使用它,但在某些情况下,我可能会要求客户将其添加为请求参数,无论如何,谢谢

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


【解决方案1】:

您可以将 ActionType 属性上的数据注释更改为使用 Range 代替 RegularExpression 吗?

[Range(1, 4)]
public int ActionType { get; set; }

【讨论】:

  • 嗨@Krishna Teja,这并不能解决我的问题,我已经采纳了你的建议并将做出改变
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
  • 1970-01-01
  • 2015-09-22
  • 2021-09-20
  • 1970-01-01
  • 2021-07-28
相关资源
最近更新 更多