Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the form value that caused the "A potentially dangerous Request.Form value was detected from the client" in MVC?

I have an MVC3 application that has a custom HandleErrorAttribute so that I can email the error. I often get the "A potentially dangerous Request.Form value was detected from the client", but it only shows the first few characters of the form value that caused the exception. I'd like to see the entire form value that was entered to try to get a better idea if the input was malicious or accidental by a user. However, when I try to pull the form values in the HandleErrorAttribute, it throws the same error! Any idea how to get the form values from the Request.Form without causing validation in my exception handler?

public class HandleErrorLogAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        base.OnException(context);

        //Record Error
        string errorDetails = HttpUtility.HtmlEncode(context.Exception.ToString());

        // Throws "otentially dangerous..." error here
        foreach (var key in context.RequestContext.HttpContext.Request.Form.AllKeys)
        {
            errorDetails += key + "=" + HttpUtility.HtmlEncode(context.RequestContext.HttpContext.Request.Form[key]);
        }

        // Send Email with errorDetails
    }
}
like image 521
Austin Avatar asked Feb 02 '12 14:02

Austin


1 Answers

In ASP.NET 4.5, you will be able to use the new HttpRequest.Unvalidated.Form property.

Until then, you can use reflection to read the private HttpRequest._form field:

HttpRequest request = context.RequestContext.HttpContext.Request;
NameValueCollection form = (NameValueCollection)request.GetType().InvokeMember(
    "_form",
    BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField,
    null, request, null);

Note that _form is lazily initialized by the HttpRequest.Form property, so make sure HttpRequest.Form has been accessed at least once beforehand.

like image 188
Michael Liu Avatar answered Oct 17 '22 15:10

Michael Liu