2012-03-21 33 views
0

我執行在一個網站丟失的密碼驗證碼填寫控制的模型屬性,如描述hereAsp.Net MVC:從ActionFilterAttribute OnActionExecuting

但我覺得很unconfortable用`

filterContext.ActionParameters [「captchaValid」] = recaptchaResponse.IsValid;

因爲:

  • 我一個強類型的視圖,以驗證
  • 的一天,我會更改屬性的名稱,無需記住這串領域,它不會工作。

所以我搜索瞭如何在ActionFilterAttribute編輯我的模型的屬性,在OnActionExecuting,因爲我的控制器行動將需要此數據。 我發現this,但不能爲我工作,因爲我需要在動作執行之前設置模型。

所以我認爲我可以添加一個「Post變量」,它將被模型綁定器讀取,但似乎filterContext.HttpContext.Request.Form處於只讀模式。

那麼你認爲我可以把結果放到我的模型中?

E.g:MyModel.IsCaptchaValid = recaptchaResponse.IsValid;

事件,如果我不能避免指定屬性字段,它比現在好:

filterContext.Something.Else["ModelKey"] = recaptchaResponse.IsValid;; 

回答

2

如何將一個錯誤的ModelState例如

filterContext.Controller.ViewData.ModelState.AddModelError("", ""Captcha response invalid") 

然後,您可以檢查ModelState.IsValid在你的行動(你應該這樣做無論如何)

+0

哼!這是非常intentant!我沒有強硬,我可以直接修改驗證狀態!大!謝謝!我需要的 – J4N 2012-03-21 12:26:54

0

的一天,我會更改屬性名稱不記得這 字符串字段,它贏得了」噸工作。

如果您擔心某個屬性/字符串名稱更改會中斷功能,您可以單元測試您的自定義屬性。

public void CaptchaValidatorAttribute_SetsActionParameter_ForCaptchaValidity() 
{ 
    // arrange 
    var filterContext = new ActionExecutingContext 
    { 
     ActionParameters = new Dictionary<string, object>() 
     // ... other arrangements, like mocking HttpContextBase and HttpRequestBase 
    }; 
    var actionFilter = new CaptchaValidatorAttribute(); 

    // act 
    actionFilter.OnActionExecuting(filterContext); 

    // assert 
    Assert.AreEqual(filterContext.ActionParameters.ContainsKey("captchaValid"), 
     true); 
} 
相關問題