Tom Gullen
Tom Gullen

Reputation: 61729

c# replace string function not returning expected results

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;"

Upvotes: 2

Views: 2860

Answers (3)

Felice Pollano
Felice Pollano

Reputation: 33242

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

Upvotes: 3

Bolu
Bolu

Reputation: 8786

I think you need to use cleanedString = cleanedString.Replace("<","&lt;"); etc.

Upvotes: 1

Zooba
Zooba

Reputation: 11438

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.

Upvotes: 7

Related Questions