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

3
  • 3
    possible duplicate of String.Replace does not seem to replace brackets with empty string... Commented Feb 22, 2011 at 10:18
  • just a note: it seems to me that you're basically duplicating the builtin HttpServerUtility.UrlEncode function (maybe it's just because you've simplified your scenario to explain your question) Commented Feb 22, 2011 at 10:22
  • Note that you have to replace & before replacing < and >, otherwise < will end up as &amp;lt; and > will end up as &amp;gt;. Commented Feb 22, 2011 at 10:22

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

In any case you probably want to use System.Web.HttpUtility.HtmlEncode, or if you're running with the .NET Client profile you can get equivalent code from Microsoft's AntiXSS library, or you could copy the HtmlEncode code into your project from Reflector
@Rup Agreed, and I upvoted the answer that suggested that, as well as answering the problem with the given code and voting to close as an exact duplicate... I feel like I've done too much work here.
3

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.