HOW TO manage the ASP.NET ValidateRequest property in different cases

Request Validation is a useful feature in ASP.NET that prevents potentially unsafe input from being submitted to the server with the ValidateRequest property.

By default, request validation is enabled in Machine.config. If a user inputs text through an ASP.NET page that has the property ValidateRequest="True", an ugly error page will be thrown. A neat way of handling this error, as shared by Kirk Allen Evans, is to override the OnError Method of the Page class & show a friendly message instead of the regular "A potentially dangerous... " message that could scare a timid user.

protected override void OnError(EventArgs e)
{
System.Exception oops = Server.GetLastError();

if(oops.GetBaseException() is System.Web.HttpRequestValidationException )
{
//System.Diagnostics.Debug.Assert(false);
//Response.Write(oops.ToString());
//Insert a friendly message asking user not to enter anything like tags.
Response.StatusCode = 200;
Response.End();
}
}

If ValidateRequest has to be set to False, you can cautiously constrain input through client & server-side validation with carefully crafted regular expressions to prevent cross-site scripting (XSS) attacks OR filter user input to allow safe HTML elements such as bold and italic tags OR fearlessly accept the input & encode output using the Server.HtmlEncode method.

Comments

Popular posts from this blog

Maven Crash Course - Learn Power Query, Power Pivot & DAX in 15 Minutes

"Data Prep & Exploratory Data Analysis" course by Maven Analytics

Oracle Cloud Infrastructure 2024 Generative AI Professional Course & Certification Exam (1Z0-1127-24)