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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With