简体   繁体   中英

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
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM