2009-07-29 44 views
1

在動作方法綁定到參數之前,有沒有辦法編輯Request.Form?我已經有了一個反射調用來啓用Request.Form的編輯。在綁定發生之前,我無法找到一個可以擴展的地方。在綁定前編輯Request.Form

更新:所以它看起來像我編輯Request.Form並沒有意識到它。我正在通過查看綁定參數進行驗證。這是不正確的b/c到達ActionFilter時,表單值已經被複制/設置到ValueProvider中。我相信這是價值觀被綁定的地方。

所以這個問題變成什麼是最好的方式來應用一些過濾到表單值之前,他們被綁定。我仍然希望綁定發生。我只想編輯它用來綁定的值。

回答

0

我結束了延長對DefaultModelBinder setProperty方法在繼續基本行爲之前檢查值。如果該值是一個字符串,我執行我的過濾。

public class ScrubbingBinder : DefaultModelBinder 
{ 
    protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value) 
    { 
     if (value.GetType() == typeof(string)) 
      value = HtmlScrubber.ScrubHtml(value as string, HtmlScrubber.SimpleFormatTags); 
     base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value); 
    } 
} 
0

創建自定義過濾器和覆蓋OnActionExecuting()

public class CustomActionFilterAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
    } 
} 

或者乾脆在你的控制器

更新的覆蓋OnActionExecuting()

protected override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
    var actionName = filterContext.ActionDescriptor.ActionName; 

    if(String.Compare(actionName, "Some", true) == 0 && Request.HttpMethod == "POST") 
    { 
     var form = filterContext.ActionParameters["form"] as FormCollection; 

     form.Add("New", "NewValue"); 
    } 
} 

public ActionResult SomeAction(FormCollection form) 
{ 
    ... 
}