How to encode strings on ASP.NET page's HTML or in URL
Very often, you need to load data from database, display user's input or work with some other uncertain data. That could be to show a string on page as title or text, or to use string to build query string part of hyperlink. The problem occurs when we don't know which characters could appear in string.
Since web pages are created by using HTML language which has its own rules, we could experience problem if string in database contains some of the reserved HTML symbols. In that case, ASP.NET web page will be displayed with syntax errors.
There are also security issues, if ASP.NET application just takes user's input and show it without check, then some malicious user is able to execute JavaScript code, show spam web page from other server by using frames or something worse.
To solve problems like this, we'll use HttpUtility class located in System.Web namespace.
How to use HtmlEncode method to display insecure text on ASP.NET page
For example, that could be showing of some article like this one, where article's title and content are stored in database. Page itself is dynamically created. To show user's input securely we'll use HtmlEncode method:
Response.Write(HttpUtility.HtmlEncode(SomePoteniallyDangerousString));
On this way, & will be replaced with & , < will become < etc., so string will be shown securely and correctly.
How to use UrlEncode method to build URLs on ASP.NET page
On similar way, to build whole hyperlink or just part of URL, we'll use UrlEncode method:
Response.Write("<a href='SomePage.aspx?theDate=" + HttpUtility.UrlEncode(SomeStringWithSymbols));
Conclusion
HtmlEncode and UrlEncode are two useful methods to securely work with potentially dangerous data. Note that you can use these methods from other classes too. Instead of HttpUtility.HtmlEncode and HttpUtility.UrlEncode, same methods you can call as Server.HtmlEncode and Server.UrlEncode respectively.
Already encoded strings can be turned back by using HttpUtility.HtmlDecode and HttpUtility.UrlDecode methods.
Happy coding!
Related articles:
1. URL Rewriting in ASP.NET
2. Dangerous paths - URI Design