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.
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:
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));
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.
1. URL Rewriting in ASP.NET
2. Dangerous paths - URI Design