I am trying to avoid an cross side scripting in my Application but my requirement is i have to save the data including the script to my database but when displaying the same data it it should be visible as a text not as a script for eg:
Step 1 : i have a textbox in a website i am trying to inject through the below code as
test data alert('Malicious Code');
Step 2 : i am saving the exact content of the text in my db (note the validateRequest is set to false).
Step 3 : Then i am dispaying the content in the web page that time the script should not execute.
Note: I have restricted it through the AntiXss and Sanitizer, but when i am using the Sanitizer the Script is neglected by the Sanitizer, Can any one give me a solution to display the script as a text (should avoid the execution of the script too.)
In your case,
"They are not supposed to work together". You are conflicting your asp.net validation with a dangerous input (though it comes via antixss library).
Validate Request = "true" is the ASP.Net security mechanism. It is intended to safeguard you from XSS attacks by filtering (using heuristics or white list, I am not sure) potentially dangerous tags in the input. For instance if you create an ASP.Net application, and if
Validate Request = "true", and when you try to input a query string parameter like
, you are gonna get "A potentially dangerous Request.Form value was detected from the cliet.. blah blah blah". That is Validate Request = "true" in action, either set at page level or web.config.
Now, the point of using an antixss library is when you have a situation like what you have now - take user input as such (with potentially dangerous input), save it somewhere, and display it back to the user - you need to turn of ASP.Net's Validate Request. And by doing that you are telling ASP.Net to leave the security of the web application to you. And you are responsible for handling XSS vulnerabilities, not ASP.Net. While saving to the database use antixss'
GetSafeHtmlFragment() method to sanitize your input. Also please note that antixss version 4.2.1 is known for strict escaping.
I suggest you evaluate your options with the antixss library, html encode. But your solution here is to turn off Validate Request. Use antixss (I would prefer Html Agility pack though) before saving to your database, and use
HtmlEncode() before displaying in the html context of the page. Rick Strahl has a sample implementation with Html Agility Pack here - http://weblog.west-wind.com/posts/2012/Jul/19/NET-HTML-Sanitation-for-rich-HTML-Input.
Be sure to read through the below questions for solid understanding, and correct implementation.