C#ASP.NET MVC手动访问Request.Form&潜在危险值 [英] C# ASP.NET MVC Manually Accessing Request.Form & Potentially Dangerous values
问题描述
我正在序列化并保存表单,并针对每个用户请求将字符串数据查询到数据库中.该特定的已提交模型已经具有[AllowHtml]属性,并且可以向控制器精细提交.问题出在我记录请求的Global.asax文件中,当我访问此表单值时出现异常:
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]));
...
}
当尝试访问Request.Form [k]包含无效字符时,将引发错误.
Error gets thrown when it tries to access Request.Form[k] when it contains invalid characters.
推荐答案
使用Request.Form[]
访问值将触发请求验证(因此为异常).您可以使用HttpRequest
的Unvalidated
属性来获取请求值,而无需触发验证.
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.
替换
Request.Form[k]
使用
Request.Unvalidated.Form[k]