简体   繁体   中英

Turn off request validation programmatically

I have a control that I'm writing where I want to turn off .NET's inbuilt request validation that prevents XSS attacks and similiar sort of nasties.

The control allows the owner of a web-site to adjust the content on that page. They can potentially enter markup if they want to. Since it's their site to edit, they must be able to stick whatever they want on there.

I'm wondering if it is possible to disable this validation programmatically?

The only way I can find to do it is either by shutting off request validation completely in the web.config or by using a page directive. For various reasons, I can't have this control in another page - so that option is out.

None of the answers outlined here go far enough. Since the configuration items are read only, you first need to modify them so that they can be written to. Additionally, since the release of .NET 4, you also need to modify the HttpRuntime.RequestValidationMode property before this Pages.ValidateRequest property will get recognised.

public void ModifiyValidation(bool validate) {

    var pagesSection = System.Configuration.ConfigurationManager.GetSection("system.web/pages") as PagesSection;
    var httpRuntime = System.Configuration.ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;

    if (pagesSection != null && httpRuntime != null && pagesSection.ValidateRequest != validate)
    {
        var fi = typeof (ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
        fi.SetValue(pagesSection, false);
        fi.SetValue(httpRuntime, false);
        pagesSection.ValidateRequest = validate;
        httpRuntime.RequestValidationMode = new Version(validate ? "4.0" : "2.0");
        fi.SetValue(pagesSection, true);
        fi.SetValue(httpRuntime, true);
    }
}

You should also be aware that the will only be activated on the following request.

In the System.Web.Configuration

PagesSection pageSection = new PagesSection();
pageSection.ValidateRequest = false;

Reference

@Chris led me in the right direction.

What I did was to turn off the setting in the web.config and used a HTTP module to do the request validation for all requests where the user is not in EditMode.

In .NET 2.0, there is a method on the Request class called: ValidateInput. This will do the validation even when it is turned off in the web.config.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM