2016-04-15 82 views
3

基于此链接https://msdn.microsoft.com/en-us/library/aa664615(v=vs.71).aspx我可以传递基元类型的单维数组。 但是,无论何时传递一个字符串数组,我都没有获得对此自定义操作筛选器属性设置的期望值。有什么我做错了吗?无法将字符串数组传递给WebApi Actionfilter

[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所需的值变量。 enter image description here

+0

对我工作的罚款。 –

+1

@AmitKumarGhosh没有配偶! – codebased

回答

1

我的测试 -

[CheckModelForNullAttribute(ExcludeArgs = new string[] { "Test" }, ErrorMessage = "error", ErrorCode = "404")] 

enter image description here

+1

嗯有趣的是,你使用的WebApi的版本是什么,我在webapi 5.2.3我也注意到我正在启动过滤器两次,即当我在构造函数上放置断点时。由于你的巨大努力,我会提高你的答案。如果您可以检查我提到的版本,那么如果最新版本发布中存在错误,则可能会回答这个问题。 – codebased

+0

嗨,大家好。我面临的问题都是针对WebApi 5.2.3传递给ActionFilterAttribute的字符串和对象数组。奇怪的是,int和double数组工作正常。你有这个问题调查的一些结果吗? –