我正在尝试理解这个ActionFilterAttribute。为了更好地理解它是如何工作的,我尝试了一下代码,但我完全迷惑了。
这是有效的ActionFilterAttribute。它应该检查空的请求体并返回一个错误:
public class CheckModelForNullAttribute : ActionFilterAttribute
{
private readonly Func<Dictionary<string, object>, bool> _validate;
public CheckModelForNullAttribute() : this(arguments => arguments.ContainsValue(null))
{ }
public CheckModelForNullAttribute(Func<Dictionary<string, object>, bool> checkCondition)
{
_validate = checkCondition;
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (_validate(actionContext.ActionArguments))
{
var modelState = new ModelStateDictionary();
modelState.AddModelError("Parameter", "The request body cannot be null");
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
}
}
}为什么这不会产生相同的结果:
public class CheckModelForNullAttribute: ActionFilterAttribute
{
private readonly Func<Dictionary<string, object>, bool> _validate = args => args.ContainsValue(null);
public override void OnActionExecuting(HttpActionContext filterContext)
{
if (!_validate(filterContext.ActionArguments))
{
filterContext.ModelState.AddModelError("Parameter", "The request body cannot be null");
filterContext.Response = filterContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, filterContext.ModelState);
}
}
}发布于 2014-07-25 14:50:16
我犯了一个愚蠢的错误:
if (_validate(actionContext.ActionArguments)) 在第一节课上
if (!_validate(filterContext.ActionArguments)) 在第二节课上。
解决方案,删除!它的工作原理是一样的。
谢谢你haim770的暗示!我想我是累了,看不见了
https://stackoverflow.com/questions/24927416
复制相似问题