Asp.net mvc 在绑定前编辑请求.表单
在action方法绑定到参数之前,是否有方法编辑Request.Form?我已经有一个反射调用来启用对Request.Form的编辑。我只是找不到一个扩展点,在绑定发生之前可以修改它 更新:看来我正在编辑请求。表单,但没有意识到。我通过查看绑定参数进行验证。这是不正确的b/c当您到达ActionFilter时,表单值已经复制/设置到/在ValueProvider中。我相信这就是拉取值进行绑定的地方Asp.net mvc 在绑定前编辑请求.表单,asp.net-mvc,binding,request,Asp.net Mvc,Binding,Request,在action方法绑定到参数之前,是否有方法编辑Request.Form?我已经有一个反射调用来启用对Request.Form的编辑。我只是找不到一个扩展点,在绑定发生之前可以修改它 更新:看来我正在编辑请求。表单,但没有意识到。我通过查看绑定参数进行验证。这是不正确的b/c当您到达ActionFilter时,表单值已经复制/设置到/在ValueProvider中。我相信这就是拉取值进行绑定的地方 所以问题变成了什么是在表单值被绑定之前对表单值应用一些过滤的最佳方式。我仍然希望绑定发生。我只想编
所以问题变成了什么是在表单值被绑定之前对表单值应用一些过滤的最佳方式。我仍然希望绑定发生。我只想编辑它用于绑定的值。创建自定义筛选器并覆盖
OnActionExecuting()
:
或者只需覆盖控制器中的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)
{
...
}
我最终扩展了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);
}
}
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);
}
}