Why is ValidateInput(False) not working?

一个人想着一个人 提交于 2019-11-27 00:38:41

Are you sure that the controller action being posted to is the one you have the attributes on?

Jim Geurts

With asp.net 4, you'll need to configure the validation mode in the web.config as well.

Set the following as a child of the <system.web> element:

<system.Web>
  ...
  <httpRuntime requestValidationMode="2.0"/>     

Asp.Net 4 sets the requestValidationMode to 4.0 by default, which tells the system to perform request validation before the BeginRequst phase of the HTTP request. The validation will occur before the system reaches the action attribute telling it not to validate the request, thus rendering the attribute useless. Setting requestValidationMode="2.0" will revert to the asp.net 2.0 request validation behavior, allowing the ValidateInput attribute to work as expected.

Rahatur

When you are using your own model binders which implement the IModelBinder interface you will notice that those custom model binders always validate the data, regardless any attributes. You can add few lines of code to make the custom model binders respect the ValidateInput filter of the actions:

// First check if request validation is required
var shouldPerformRequestValidation = controllerContext.Controller.ValidateRequest && bindingContext.ModelMetadata.RequestValidationEnabled;

// Get value
var valueProviderResult = bindingContext.GetValueFromValueProvider(shouldPerformRequestValidation);
if (valueProviderResult != null)
{
    var theValue = valueProviderResult.AttemptedValue;

    // etc...
}

This is explained very nicely by Martijn Boland here: http://blogs.taiga.nl/martijn/2011/09/29/custom-model-binders-and-request-validation/

Frank van Eykelen

Please note that these suggestions will not fix the problems caused by a bug that occurs when you have to use [ValidateInput(false)] in combination with a FormCollection.

See: ASP.NET MVC 3 ValidateRequest(false) not working with FormCollection

You can try accessing the field like HttpContext.Request.Unvalidated.Form["FieldName"]

If you use an input model and use an AllowHtml on the property you want, you will be unblocked.

public class InputModel
{
    [AllowHtml]
    public string HtmlInput { get; set; }
}

...
[ValidateInput(false)]
public async Task<ActionResult> ControllerMethod(InputModel model)
{
}

Add the following line of code:

GlobalFilters.Filters.Add(new ValidateInputAttribute(false));

to the Application_Start() method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!