Escape C # String for HTML

I have a line with special characters like:

äöüß &

Now I want to put this in an HTML document and avoid these characters. Is there an elegant way to do this?

I could do this:

string html; html = html.Replace("ü", "uu¨"); html = html.Replace("ß", "ß"); .... 

But I do not want to do this for all possible special characters.

+4
source share
3 answers

Why not let the Framework work for you?

You can try HtmlEncode :

 string encodedHtml = Server.HtmlEncode(html); 
+13
source

There is also this for XML, but it should work fine with HTML:

System.Security.SecurityElement.Escape( string s );

+8
source

I recommend getting used to using the Microsoft AntiXSS Library and calling

 AntiXSS.HtmlEncode(yourstring); 

if you need to include it in the body, or

 AntiXSS.HtmlAttributeEncode(yourstring); 

if it is included in the html attribute.

+1
source

Source: https://habr.com/ru/post/1388974/


All Articles