![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXGvIAl2jxa6_538TQXKxT_bpv5SN071MboOIQcWE1zQkCFYgnTEaDi8wSfbdYOJ1tw8FaszxdPwMYIUcQ8uf1uUNbbCynXm3cpvYeoVzqM-mAxTjacqvqmw79u8Mbr5-ZUGIHsq8aiwxa/s640/%25E8%259E%25A2%25E5%25B9%2595%25E5%25BF%25AB%25E7%2585%25A7+2016-10-25+%25E4%25B8%258A%25E5%258D%25889.53.04.png)
但為了效能跟 ISO 8601 日期格式考量
在我們開發的系統中就把 JavaScriptSerializer 給換成 Json.Net 了 (如下 & 作法的參考網址)
///
/// 複寫原本的 Json Result
///
protected override JsonResult Json(object data,
string contentType,
System.Text.Encoding contentEncoding,
JsonRequestBehavior behavior)
{
return new JsonNetResult()
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding
};
}
///
/// Json.Net Result
///
public class JsonNetResult : JsonResult
{
public JsonSerializerSettings SerializerSettings { get; set; }
public Formatting Formatting { get; set; }
public JsonNetResult(){ }
public override void ExecuteResult(ControllerContext context)
{
if (context == null) throw new ArgumentNullException("context");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType =
!string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data != null)
{
JsonTextWriter writer = new JsonTextWriter(response.Output)
{
Formatting = Formatting
};
JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
serializer.Serialize(writer, Data); writer.Flush();
}
}
}
好問題來惹...
改完之後發現原本上面那段回應 Javascript 的 Json Result 不 encode 了
直接把 script 吐到 client 去 TAT
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiUpUG7P3trF6-jfxaluvMpUIjqZ4WnOyd7X4ccnG_8hdScF478rDTZQRVxHHrVqIJb4No2zxF45_J-6DxjsbX7za7Vd1_Jk5xIfoL3Z69hJljY5ADJ1y7jZcJhahzpmg_Sz_BLddeogo6j/s1600/%25E8%259E%25A2%25E5%25B9%2595%25E5%25BF%25AB%25E7%2585%25A7+2016-10-25+%25E4%25B8%258A%25E5%258D%258810.08.35.png)
如果要一個一個 property 都給他 htmlEncode 過才丟給 JsonNetResult 來處理那未免也太蠢
稍微檢視一下參考(?)來的程式,發現 JsonSerializerSettings 可能會是一個切入點
查了一下 newtonsoft 的說明發現裡面有個 StringEscapeHandling 可以指定!!
在 JsonNetRsult 的建構子中加入幾行
public JsonNetResult()
{
SerializerSettings = new JsonSerializerSettings()
{
StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
}
再重新跑一次剛剛的 Action
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgL0NPP7nFPJKaIHM4YwdtaLlRaj4N8kVKeNeFOLcYX5LiYFPgIVZpvX_nCMI2mXxAHGiCQ7lFAYeUn1DmDJRnEvTumJK8DXgGyOQux-YH1ZzMpYf7Ll7Ixp1h_Nq1jLWKPvmLAhYKXxYfl/s400/%25E8%259E%25A2%25E5%25B9%2595%25E5%25BF%25AB%25E7%2585%25A7+2016-10-25+%25E4%25B8%258A%25E5%258D%258810.19.18.png)
html tag 成功被 encode 了!!
--
是說在考量效能時有考慮使用 Jil 但卡在 EscapeHtml 這個問題上,就沒有轉換成這個
沒有留言:
張貼留言