Edit Request.Form before Binding
-
05-07-2019 - |
Question
Is there a way to edit the Request.Form before the action method binds to the parameters? I already have a reflection call to enable editing of Request.Form. I just can't find a point of extensibilty where I can alter it before binding occurs.
UPDATE: So it looks like I was editing the Request.Form and didn't realize it. I was verifying by looking at the bound parameters. That is incorrect b/c by the time you get to the ActionFilter the form values have already been copied/set to/in the ValueProvider. Which I believe is where the values are pulled for binding.
So the question becomes what is the best way to apply some filtering to the form values before they are bound. I still want the binding to occur. I just want to edit the values it uses to bind.
Solution 2
I ended up extending the SetProperty method on the DefaultModelBinder to check the value before proceeding with the base behavior. If the value is a string I perform my filtering.
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);
}
}
OTHER TIPS
Create custom filter and override OnActionExecuting()
:
public class CustomActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
}
}
Or simply override OnActionExecuting()
in your controller
UPDATED:
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)
{
...
}