基于此链接https://msdn.microsoft.com/en-us/library/aa664615(v=vs.71).aspx我可以传递原始类型的一维数组。 但是,每当我传递字符串数组时,我都没有获得针对此自定义操作筛选器属性设置的所需值。我做错了什么吗?
[AttributeUsage(AttributeTargets.Method, Inherited = true)]
public class CheckModelForNullAttribute : ActionFilterAttribute
{
private readonly Func<Dictionary<string, object>, string[], bool> _validate;
public string ErrorMessage { get; set; }
public string ErrorCode { get; set; }
public string[] ExcludeArgs { get; set; }
public CheckModelForNullAttribute( )
: this((objects, excludedArgs) => objects.ContainsValue(null) && excludedArgs.Any(objects.ContainsKey) == false)
{
}
public CheckModelForNullAttribute(Func<Dictionary<string, object>, string[], bool> checkCondition)
{
_validate = checkCondition;
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (_validate(actionContext.ActionArguments, ExcludeArgs))
{
actionContext.ModelState.AddModelError("EmptyModel", ErrorMessage);
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, actionContext.ModelState.ValidationErrors(ErrorCode));
}
}
}
它的用途是:
[CheckModelForNullAttribute(ExcludeArgs = new[] { "requests"}, ErrorMessage = Constants.GenericErrors.DefaultError )]
public HttpResponseMessage Create([FromBody] CreateAccountsRequest requests)
{ }
在调试时,当光标移至 _validate(...) 条件时,字符串数组的值为空,因为我在
ErrorMessage
变量中有所需的值。