#事故現場
在一個asp.net 的項目中,前端通過ajax將富文本中的文字內容post到服務端的一個ashx中,在ashx中嘗試讀取參數值時,
結果報錯:“從客戶端中檢測到有潛在危險的 Request.Form 值”
#事故分析
由於在asp.net中,Request提交時出現有html代碼字符串時,程序系統會認為其具有潛在危險的值。會報出“從客戶端 中檢測到有潛在危險的Request.Form值”這樣的Error。
而富文本中的內容是包含html代碼的,所以...
#解決方案:
1、前端對富文本字符串進行encodeURI編碼,服務端進行HttpUtility.UrlDecode解碼操作;
前端代碼:
var str = '<p><span style="color: #00B0F0;"><em><strong>我想留在你的身邊,</strong></em></span><br/></p><p><span style="color: #7030A0;"><strong><span style="text-decoration: underline;">深情款款多么可憐;</span></strong></span></p>'; $(function() { $.ajax({ type: "post", url: "TestHandle.ashx", data: { Title: 'jack', Content: encodeURI(str) }, success: function (data) { $("#div").html(data); } }); });
后端代碼:
public void ProcessRequest(HttpContext context) { string str = context.Request["content"]; string content = HttpUtility.UrlDecode(str); context.Response.ContentType = "text/plain"; context.Response.Write(content); }
2、前端不以form的方式提交,直接以json方式提交,服務端從request的body中讀取數據,然后反序列化,得到信息;
前端代碼:
var str = '<p><span style="color: #00B0F0;"><em><strong>我想留在你的身邊,</strong></em></span><br/></p><p><span style="color: #7030A0;"><strong><span style="text-decoration: underline;">深情款款多么可憐;</span></strong></span></p>'; var temp = { Title: 'jack', Content: str }; $.ajax({ type: "post", url: "TestHandle.ashx", contentType:"application/json;charset=utf-8", data: JSON.stringify(temp), success: function (data) { $("#div").html(data); } });
后端代碼:
string bodyText; using (var bodyReader = new System.IO.StreamReader(context.Request.InputStream)) { bodyText = bodyReader.ReadToEnd(); } dynamic bodyObj = JsonConvert.DeserializeObject(bodyText); context.Response.ContentType = "text/plain"; context.Response.Write(bodyObj.Content);
#其他場景的解決方案:
1、aspx頁面,當前頁面進行form提交
打開當前.aspx頁面,頁頭加上代碼:validateRequest=”false”,如:
<%@ Page Language="C#" ValidateRequest="false" AutoEventWireup="false" CodeFile="default.aspx.cs" Inherits="default" %>
該方法不推薦,還有一種修改web.config配置文件的方法,強烈不推薦,就不寫在這里了;
2、在ASP.NET MVC中的解決方案
1)、針對某個實體類的單個字段設置 [AllowHtml] ,這樣提交的時候,系統就會放過該字段。
前端代碼:
var str = '<p><span style="color: #00B0F0;"><em><strong>我想留在你的身邊,</strong></em></span><br/></p><p><span style="color: #7030A0;"><strong><span style="text-decoration: underline;">深情款款多么可憐;</span></strong></span></p>'; $(function () { $.ajax({ type: "post", url: "Home/Test", data: { Title: 'jack', Content: str }, success: function (data) { $("#div").html(data.ok); } }); });
后端代碼
public class NewInfo { public string Title { get; set; } [AllowHtml] public string Content { get; set; } }
public ActionResult Test(NewInfo info) { return Json(new { ok = info.Content}); }
2)、直接根據當前Action方法不做判斷的方法,在Action前加上 [ValidateInput(false)]
代碼如下
[ValidateInput(false)] [HttpPost] public ActionResult Edit() { 。。。。 return Redirect("/product"); }
參考原文鏈接:https://www.cnblogs.com/willingtolove/p/10923895.html