Tuesday, 20 November 2007


You may stumble across the following exception when working with inputing html through a form:

Exception type: HttpRequestValidationException Exception message: A potentially dangerous Request.Form value was detected from the client

This is .Net attempting to protect us from a potentially malicious input form value, which is sweet ...but sometimes unwanted. To avoid the exception being thrown you need to do two simple things:

1. Add the validateRequest page directive to the aspx page, and set to false OR to disable for your entire web application update your web.config:

<%@ Page language="c#" validateRequest="false" Codebehind="TestForm.aspx.cs" ... %>
... OR ...
   <pages validaterequest="false">

2. Manually diffuse any potentially malicous input form values in the code behind:

string formFieldValue = Server.HtmlEncode(Request[ "FormKeyValue"]);
string queryValue = Server.UrlEncode(Request.Query["QueryKeyValue"]);

All step 2 does is escape characters, e.g. < is replaced with &lt;

WARNING !!! If you don't validate the input data manually, like in step 2, you could leave your application vulnerable to cross site scripting or injection attacks. Infact, I recommend that you validate input data manually anyway, as the request validation performed by .Net isn't bullet proof

No comments: