Monday, December 26, 2011

Avoid "A potentially dangerous" error in MVC 2.0





When we need to post some HTML contents on server side, on form post in MVC 2.0, we can simplay write ValidateInput(false) above method declaration to avoid run time unhandled exception : "A potentially dangerous Request.Form value was detected from the client"


The complete syntax for the same is as follows


[AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
public ActionResult Save(YourViewModel model)
{
}


Additionally we need to do following setting (only for net 4.0) along with above solution,


With asp.net 4, we will need to configure the validation mode in the web.config as well.


Set the following as a child of the <system.web> element:
<httpRuntime requestValidationMode="2.0"/>


Asp.Net 4 sets the requestValidationMode to 4.0 by default, which tells the system to perform request validation before the BeginRequst phase of the HTTP request. The validation will occur before the system reaches the action attribute telling it not to validate the request, thus rendering the attribute useless. Setting requestValidationMode="2.0" will revert to the asp.net 2.0 request validation behavior, allowing the ValidateInput attribute to work as expected.




Thanks for Reading
Happy Programming :)


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
Happy Programming :)