ashx生成html的,在我的.ashx HtmlEncode

博客探讨了在处理用户输入时,为何直接HTML编码JSON可能是不必要的。文章提供了一个示例,展示如何在构造JSON对象前对不可信的用户输入进行编码,确保数据安全。示例代码展示了在ASHX处理程序中生成JSON响应的方法,包括如何构造包含图片信息的JSON对象,并使用jQuery进行AJAX请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我不认为HTML编码JSON是有道理的。如果你在JSON对象中有不可信的值,那么你在构造JSON对象之前先对它们进行编码。

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 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 =

"'\"{1}\"

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 GetImages()

{

IList list = new List();

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:

Get Json

$(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);

}

});

});

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值