You can get more fine-grained control over this by setting the requestValidationType
attribute of the httpRuntime
element to a custom type that inherits from System.Web.Util.RequestValidator
and overrides IsValidRequestString
.
Unfortunately this isn't part of the WebAPI pipeline, so can't directly check for things like action filters (i.e. attributes on controller methods).
However, if you specifically care about the Validation of Form fields, the Validator doesn't get called on these until you access them, which happens after Action Filters are fired, so you can opt-out of validation using an attribute by creating classes like the following...
public class AllowFormHtmlAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
HttpContext.Current.Items["AllowFormHtml"] = true;
}
}
public class CustomRequestValidator : RequestValidator
{
protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
{
if (context.Items["AllowFormHtml"] as bool? == true && requestValidationSource == RequestValidationSource.Form)
{
validationFailureIndex = 0;
return true;
}
return base.IsValidRequestString(
context, value, requestValidationSource, collectionKey, out validationFailureIndex);
}
}
... Then just annotating your controller method with [AllowFormHtml]
However, if you're accessing form fields directly from the HttpRequest, it's simpler to use HttpRequest.Unvalidated
, which bypasses validation.
requestValidationMode='2.0'
to the web.config and trying the[ValidateInput(false)]
attribute on the action method did NOT work. It started working after I addedrequestPathInvalidCharacters=""
. I think this is because the error here is part of Request.Path validation rather than Request.Form validation. – Occur