Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# replace string function not returning expected results

Tags:

string

c#

string message = CommonFunctions.SanitiseInput(context.Request.QueryString["msg"]);

And the function is defined as:

// Sanitise input
public static string SanitiseInput(string inputText)
{
    string cleanedString = inputText;

    cleanedString.Replace("<","&lt;");      // No code
    cleanedString.Replace(">", "&gt;");
    cleanedString.Replace("&", "&amp;");    // No query string breaks

    return cleanedString;
}

Given input "<b>rg</b>" this returns the same, and not "&lt;b&gt;rg&lt;/b&gt;"

like image 656
Tom Gullen Avatar asked Apr 07 '26 07:04

Tom Gullen


2 Answers

The Replace function in C# does not modify the string itself - it returns a modified version of the string.

Try this:

public static string SanitiseInput(string inputText)
{
    string cleanedString = inputText;

    cleanedString = cleanedString.Replace("<","&lt;");      // No code
    cleanedString = cleanedString.Replace(">", "&gt;");
    cleanedString = cleanedString.Replace("&", "&amp;");    // No query string breaks

    return cleanedString;
}

For "<b>rg</b>" this will give you "&amp;lt;b&amp;gt;rg&amp;lt;/b&amp;gt;". To fix up the unnecessary conversions to "&amp;", move the third replacement to before the other two, which will give you the result you are expecting.

like image 129
Zooba Avatar answered Apr 08 '26 20:04

Zooba


You should use HttpUtility.HtmlEncode(): http://msdn.microsoft.com/en-us/library/system.web.httputility.htmlencode.aspx

like image 37
Felice Pollano Avatar answered Apr 08 '26 21:04

Felice Pollano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!