XSS Prevention: Safeguarding Your Website Against Cross-Site Scripting

Here's an example of how to prevent XSS in C# for text and object:

For Text

string inputText = "<script>alert('XSS Attack!');</script>";
string sanitizedText = System.Web.HttpUtility.HtmlEncode(inputText);

The HttpUtility.HtmlEncode() method is used to encode any special characters in the input text, including HTML tags and script elements. This ensures that the text is safe to display on a web page and cannot be used to execute a malicious script.

For Objects

using System.Web.Script.Serialization;
// ...

public static string SerializeObjectWithoutXSS(object obj)
{
    var serializer = new JavaScriptSerializer();
    serializer.RegisterConverters(new JavaScriptConverter[] { new MyCustomConverter() });
    var serializedObj = serializer.Serialize(obj);
    return serializedObj;
}

public class MyCustomConverter : JavaScriptConverter
{
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        // We don't need to implement this method for XSS prevention.
        throw new NotImplementedException();
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        var result = new Dictionary<string, object>();
        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(obj))
        {
            var value = property.GetValue(obj);
            if (value != null)
            {
                var serializedValue = serializer.Serialize(value);
                var sanitizedValue = System.Web.HttpUtility.HtmlEncode(serializedValue);
                result.Add(property.Name, sanitizedValue);
            }
        }
        return result;
    }

    public override IEnumerable<Type> SupportedTypes
    {
        get { return new Type[] { typeof(object) }; }
    }
}

In the code snippet above, we're using the JavaScriptSerializer class to serialize an object to a JSON string, but before doing so, we're encoding any special characters in the serialized value using the HttpUtility.HtmlEncode() method. We're doing this by creating a custom converter that inherits from JavaScriptConverter and overrides the Serialize method. This method loops through all the properties of the object, serializes their values, and then sanitizes those values using HtmlEncode() before adding them to a dictionary that is returned as the serialized JSON object. Doing this ensures that any special characters in the object's properties are properly encoded and cannot be used to execute malicious scripts.