tags:

views:

411

answers:

3

How can I HtmlEncode my JSON from within my .ashx?

context.Response.Write(HtmlEncode(jsonString));

I added System.Web.HttpUtility using to the top of my .ashx but no luck

A: 

nevermind, I preceeded it with HttpUtility.HtmlEncode

CoffeeAddict
A: 

I don't think HTML Encoding JSON makes any sense. If you have untrusted values in JSON object, then you html encode them before constructing JSON object.

 string fromMaliciousUser=".............";;

 string json="{'userInput':'"+HttpUtility.HtmlEncode(fromMaliciousUser)+"'}";

EDIT: I've tried this code and it returns the JSON NICELY :)

CODE IN 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>
TheVillageIdiot
I don't get you can you explain in different words
CoffeeAddict
ok, then in that case check out this url: api.flickr.com/services/feeds/… why does it show up so nicely and with no unicode crap? View source and check it out. It's using that url above to get the data and then uses .description which includes some HTML already
CoffeeAddict
I meant http://api.flickr.com/services/feeds/photos_public.gne?format=json
CoffeeAddict
so why does that flickr url return for example description with a string that include valid HTML and none of these weird encode character sh** ? sorry just irritable today.
CoffeeAddict
CoffeeAddict
I've added some code that you may try. But if you really want to return complex json objects like the ones from flickr.com I would suggest you some JSON library for .Net like from http://james.newtonking.com/pages/json-net.aspx, http://code.google.com/p/jsonsharp/ etc. They provide higher level of abstraction and save you from getting insane with braces, brackets and quotes.
TheVillageIdiot
-1 because you not only shouldn't be using "HtmlEncode", but building a JSON response with StringBuilder is a disaster waiting to happen. As of .NET 3.5+ you have a built-in class "JavaScriptSerializer", that properly serializes objects, arrays, strings, numbers, dates etc. from .NET to their JavaScript equivalents.
Milan Gardian
Dear @Milan has @coffeeaddict anywhere mentioned that .Net 3.5 is being used?
TheVillageIdiot
@TheVillageIdiot: no, @coffeeaddict did not specify his target platform. But I wasn't posting an answer, I added a comment that I didn't find your answer adequate. And oh by-the-way-if-you're-'lucky'-enough-to-be-using-.NET3.5-there's-a-class-for-what-you-need. My problem with answers like yours is that people might search for this problem and see 'other people are using string builder to solve this, great, lemme do that too'. And you do realize that your implementation will break as soon as you have an image with title "Snapshot of 'El Capitan'".
Milan Gardian
@TheVillageIdiot: I would suggest you edit your answer by including and highlighting your comment about using a JSON library as the recommended technique (you could also mention the serializer class available as of .NET3.5+), with your ASHX code included as a simple naive implementation with stated caveats. Then I will not only remove my downvote but I will upvote your answer. Cheers.
Milan Gardian
A: 

I'm pretty sure that the AntiXssLibrary (version 1.5 or version 3.0 beta) has a JavaScriptEncode method: is this what you are after?

Ian Oxley
no, trying to figure out how to get my JSON to show like http://api.flickr.com/services/feeds/photos_public.gne?format=json where it doesn't have any encoding junk in it coming over the wire
CoffeeAddict