Brad
Brad

Reputation: 1684

C# ASP.NET MVC Manually Accessing Request.Form & Potentially Dangerous values

I'm serializing and saving form and query string data to a database for each user request. This particular submitted model already has the [AllowHtml] attribute and submits fine to the controller. The issue is inside the Global.asax file where I log the request, when I access this form value I get the exception:

"A potentially dangerous Request.Form value was detected from the client (...)."

protected void Application_PostRequestHandlerExecute(Object sender, EventArgs e)
{
    ...
    var serializer = new JavaScriptSerializer();
    var formData = (Request.Form.Count == 0) ? "" : serializer.Serialize(Request.Form.AllKeys.Where(x => x != null).ToDictionary(k => k, k => Request.Form[k]));
    ...
}

Error gets thrown when it tries to access Request.Form[k] when it contains invalid characters.

Upvotes: 3

Views: 7759

Answers (1)

user3559349
user3559349

Reputation:

Accessing values with Request.Form[] will trigger request validation (hence the exception). You can use the Unvalidated property of HttpRequest to get the request values without triggering validation.

Replace

Request.Form[k]

with

Request.Unvalidated.Form[k]

Use with caution - from the documentation:

Security Note: If you use this property, you must manually check the data for potential cross-site scripting attacks.

Upvotes: 4

Related Questions