ashx 修改部分 html,我的.ashx中的HtmlEncode

我认为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 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);

}

});

});

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值