【发布时间】: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