Mental Jetsam

By Peter Finch

ASP.NET catch “A potentially dangerous Request”

Posted by pcfinch on April 7, 2011

ASP.NET has a handy little feature enabled that filters requests that may be dangerous from the application. One of these is a check for HTML code that may be in a response field in order to avoid the possibility of injecting malicious code onto websites. It’s a nice security feature, and easy to disable by just adding “ValidateRequest=’false'” to the Page directive.


<%@ Page Language="C#" MasterPageFile="~/site.master" AutoEventWireup="true" CodeFile="myWebPage.aspx.cs" Inherits="details" Title="Test" ValidateRequest="false"%>

However, if you want to leave it turn on but avoid the nasty C# exception, that gets thrown when it happens, you can either override the default error page in ASP.NET or the following code can catch (trap) the HttpRequestValidationException exception and render a custom message, or redirect to your own error page.

public partial class myWebPage: System.Web.UI.Page {
 virtual public void ProcessRequest(HttpContext context) {
   try {
     Page.ProcessRequest(context);
   } catch (HttpRequestValidationException) {
     context.Response.Write("Danger");
   }
 }
}

I’m not sure if this is the official way to do it, but it works.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: