在action方法绑定参数之前,有没有办法编辑Request.Form?我已经有一个反射调用来启用Request.Form的编辑。我只是找不到可扩展点,我可以在绑定发生之前改变它。

更新:所以看起来我正在编辑Request.Form但没有意识到。我通过查看绑定参数进行验证。到达ActionFilter时,这是不正确的b / c,表单值已经被复制/设置为ValueProvider中的/。我认为这是为了约束价值的地方。

因此问题变成了在绑定之前对表单值应用某些过滤的最佳方法是什么。我仍然希望绑定发生。我只想编辑它用来绑定的值。

有帮助吗?

解决方案 2

我最终在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);
    }
}

其他提示

创建自定义过滤器并覆盖 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)
{
    ...
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top