Search code examples
c#asp.net-mvcrazorencodingspecial-characters

How to encode ç ö ü in a secure way?


I'm trying to implement a turkish content manager using c# MVC Razor.

I know I can use @Html.Raw(model.content) in order to get non-encoded texts, but this can also create some security issues, Xss, injections etc..

Instead if I just use @model.content to display text directly, I'm getting the following html source, which I think could create SEO issues as well

@model.content outputs : ......güvece dökün.......

The original text was

@Html.Raw(model.content) outputs : ......güvece dökün.......

How to avoid mvc to encode following charcter and keep html secure at the same time ?

ç, ü , ö

Of course I can create my own html extention, but I'd like to know if there is a secure and reliable method of this?


Solution

  • As i mentioned on my question , i sorted it out using html helper extesion

       @{
        string v = "<script>I Ğ Ü İ Ş Ç Ö ö ç i ş ü ğ ı ü ğ p ı o . ö ö ç ı ı n ü ğ ş a l e r t'\'\\'(x)</script>";
            @Html.SafeHtml(v);
            @Html.SafeHtmlV2(v);
        }
    
    //code above outputs: &lt;script&gt;I Ğ Ü İ Ş Ç Ö ö ç i ş ü ğ ı ü ğ p ı o . ö ö ç ı ı n ü ğ ş a l e r t&#39;&#39;\&#39;(x)&lt;/script&gt
    

    And my extension classs as follows, you can choose to replace characters one by one (method SafeHtmlV2) or interate usign an array (method SafeHtml),

    public static class MyHelper
    {
        public static MvcHtmlString SafeHtml(this HtmlHelper html, string input)
        {
            string[] decodeItems = new string[] { "&#252;", "&#246;", "&#231;", "&#220;", "&#199;", "&#214;" };
            string str = System.Net.WebUtility.HtmlEncode(input);
            foreach (string s in decodeItems)
            {
                str = str.Replace(s, System.Net.WebUtility.HtmlDecode(s));
            }
            return new MvcHtmlString(str);
        }
    
        public static MvcHtmlString SafeHtmlV2(this HtmlHelper html, string input)
        {
            string str = System.Net.WebUtility.HtmlEncode(input).Replace("&#252;", "ü")
                   .Replace("&#246;", "ö")
                   .Replace("&#231;", System.Net.WebUtility.HtmlDecode("&#231;"))
                   .Replace("&#220;", System.Net.WebUtility.HtmlDecode("&#220;"))
                   .Replace("&#199;", System.Net.WebUtility.HtmlDecode("&#199;"))
                   .Replace("&#214;", System.Net.WebUtility.HtmlDecode("&#214;"));
            return new MvcHtmlString(str);
        }
    
    }