如何在我的.ashx中对我的JSON进行HtmlEncode? p>
context.Response.Write(的HTMLEncode(jsonString));
我在我的.ashx顶部添加了System.Web.HttpUtility,但没有运气
答案 0 :(得分:0)
我非常确定AntiXssLibrary(version 1.5或version 3.0 beta)有一个 JavaScriptEncode 方法:这就是你所追求的吗?
答案 1 :(得分:-1)
我认为HTML编码JSON没有任何意义。如果在JSON对象中有不受信任的值,那么在构造JSON对象之前对它们进行html编码。
string fromMaliciousUser=".............";;
string json="{'userInput':'"+HttpUtility.HtmlEncode(fromMaliciousUser)+"'}";
编辑:我已经尝试过这段代码并且它返回了JSON NICELY:)
ASHX的代码:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class JsonReturning : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{WriteJson(context);}
private void WriteJson(HttpContext context)
{
IList<ImageDetails> images =
GetImages();//Here you should get your images;
//json contains Images object whose value is array ([)
StringBuilder sb = new StringBuilder("{'Images':[");
//all values in array quoted in (') and separated with (,)
string imgFmt =
"'<img src=\"{0}\" alt=\"{1}\" height=\"{2}px\"
width=\"{3}px\" />',";
foreach (var i in images)
{
sb.AppendFormat(imgFmt, i.ImageSrc, i.Title,
i.Height, i.Width);
}
sb.Remove(sb.Length - 1, 1);//remove last ','
sb.Append("]}");//close array (]) and object (})
context.Response.Clear();
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Write(sb.ToString());
}
public bool IsReusable{get{return false;}}
private IList<ImageDetails> GetImages()
{
IList<ImageDetails> list = new List<ImageDetails>();
list.Add(new ImageDetails() { ImageSrc = @"/images/image1.jpg",
Title = "Image1", Height = 124, Width = 124 });
list.Add(new ImageDetails() { ImageSrc = @"/images/image2.jpg",
Title = "Image2", Height = 124, Width = 124 });
list.Add(new ImageDetails() { ImageSrc = @"/images/image3.jpg",
Title = "Image3", Height = 124, Width = 124 });
list.Add(new ImageDetails() { ImageSrc = @"/images/image4.jpg",
Title = "Image4", Height = 124, Width = 124 });
list.Add(new ImageDetails() { ImageSrc = @"/images/image5.jpg",
Title = "Image5", Height = 124, Width = 124 });
return list;
}
}
internal class ImageDetails
{
internal string ImageSrc{get;set;}
internal string Title { get; set; }
internal int Height { get; set; }
internal int Width { get; set; }
}
HTML:
<div id="divJsonList" style="width:70%;height:200px;clear:both;border:1px solid
blue;"></div>
<div id="jButton" style="cursor:pointer;font-weight:bolder;">Get Json</div>
<script type="text/javascript">
$(document).ready(function() {
$("#jButton").click(function() {
$.ajax({
url: 'GetImages.imj',
type: 'POST',
data: "{'a':'b'}",
dataType: 'json',
contentType: 'application/json;charset:utf-8',
success: function(res, status) {
$("#divJsonList").text(res.Images);
},
error: function(x, s, e) {
alert(e);
}
});
});
});
</script>