[英]Passing a HTML parameter through AJAX to C# MVC Controller Action
我试图通过以下方式将HTML字符串作为参数传递:
$.ajax({
url: sourceUrl,
type: "GET",
cache: false,
success: function (data, status, jqxhr) {
etc...
}
其中sourceURL是对C#控制器操作的调用,该操作的参数包含HTML字符串(来自RTF文本框)。 就像是:
var sourceURL = "ThisController/ThisAction?Parameter=" + varWithHTML;
但是它未能说明:
从客户端检测到一个潜在危险的Request.QueryString值
(description="<p>Rich Text String</p>")
。
我试过将字符串包装在encodeURI()中:
encodeURIComponent(varWithHTML)
但仍然是同样的问题。 对于web.config中的这个问题,我还有另一个建议:
<httpRuntime requestValidationMode="2.0" />
而且仍然没有运气。 我会生气还是有办法解决这个问题?
您应该使用POST方法,并将html主体作为Post主体传递,还需要关闭ValidateInput
,您只需要将此行放在操作上方:
[ValidateInput(false)]//This line is to let you pass html in parameters.
public ActionResult ThisAction()
但是要小心 ! 这可能会使您的网站面临跨站点脚本攻击(XSS)的风险,这可能使黑客可以在请求传递时轻松编辑请求并将JavaScript放入其中。 您可能需要手动处理该操作,因为出于这个原因创建了ValidateInput
。
为了避免这种情况,您需要通过Html编码传递输入,并为每个只允许使用的标记替换每个括号,例如:
您只想启用标签<b> </b>
,则需要替换<b>
到<b>
和</b>
</b>
然后再将它们保存到数据中或对其进行任何操作!
[ValidateInput(false)]//This line is to let you pass html in parameters.
public ActionResult ThisAction(string htmlString)
{
StringBuilder sbHtmlString = new StringBuilder();
// Encode the htmlString.
sbHtmlString.Append(HttpUtility.HtmlEncode(htmlString));
// Only decode bold tag and ignore anything else!
sbHtmlString.Replace("<b>", "<b>");
sbHtmlString.Replace("</b>", "</b>");
htmlString = sbHtmlString.ToString();
//Do whatever you want with htmlString
return View();
}
祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.