Tuesday, December 27, 2011

Unescaping unicode characters in C#, encoded in JavaScript

Recently I came across a problem where I need to post HTML content (through JSON) in AJAX call and was end up getting "A potentially dangerous Request.Form value was detected from the client"


This problem lead me to learn a new thing which I thought may helpful programmers in many cases.


The problem:


I used java script escape funnction to encode html contents which I need to decode on the server side.
JavaScript escape and unescape are very powerful functions, but they do have its various idiosyncrasies that do not work appropriately with the standard escaping methods in the serverside C# code.


The regualr methods we have on C# to handle escaping/unescaping are:


  • Uri.EscapeDataString
  • Uri.EscapeUriString
  • HttpUtility.UrlEncode
  • HttpUtility.URLPathEncode

but none of these return a properly unescaped string as escaped by the JavaScript conterpart. 


The solution:

Fortunately for us, Microsoft's own JScript libary has it's own, serverside implementation of the JavaScript encode/unencode methods, that do the job exactly as expected. They are exact equivalents.


  • Microsoft.JScript.GlobalObject.unescape(string escapedString) 
  • Server.UrlDecode(Microsoft.JScript.GlobalObject.unescape(string escapedString))

To use it in your code: Reference Micrtosoft.JScript.dll in your project.
Use the static methods in GlobalObject to do the escape/unescape


Thanks for Reading..

No comments:

Find a cool free stuff everyday

Giveaway of the Day

Hiren Bharadwa's Posts

DotNetJalps