2016-04-15 87 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數組工作正常。你有這個問題調查的一些結果嗎? –