Do I have to use some library such as Gans.XSS.HtmlSanitizer or is there some inbuilt feature in Blazor.
The Blazor does not have a built-in feature to sanitizes the inputs, such as InputText
. So I create a custom DbCommandInterceptor
and sanitizes the all input before I save them into the database such as follow:
public class CorrectCommandInterceptor : DbCommandInterceptor
{
public override InterceptionResult<DbDataReader> ReaderExecuting(
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result)
{
ApplyCorrectCommand(command);
return result;
}
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result,
CancellationToken cancellationToken = new CancellationToken())
{
ApplyCorrectCommand(command);
return ValueTask.FromResult(result);
}
public override InterceptionResult<int> NonQueryExecuting(
DbCommand command,
CommandEventData eventData,
InterceptionResult<int> result)
{
ApplyCorrectCommand(command);
return result;
}
public override ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(
DbCommand command,
CommandEventData eventData,
InterceptionResult<int> result,
CancellationToken cancellationToken = new CancellationToken())
{
ApplyCorrectCommand(command);
return ValueTask.FromResult(result);
}
public override InterceptionResult<object> ScalarExecuting(
DbCommand command,
CommandEventData eventData,
InterceptionResult<object> result)
{
ApplyCorrectCommand(command);
return result;
}
public override ValueTask<InterceptionResult<object>> ScalarExecutingAsync(
DbCommand command,
CommandEventData eventData,
InterceptionResult<object> result,
CancellationToken cancellationToken = new CancellationToken())
{
ApplyCorrectCommand(command);
return ValueTask.FromResult(result);
}
private static void ApplyCorrectCommand(DbCommand command)
{
command.CommandText = command.CommandText.ApplyCorrect();
foreach (DbParameter parameter in command.Parameters)
{
switch (parameter.DbType)
{
case DbType.AnsiString:
case DbType.AnsiStringFixedLength:
case DbType.String:
case DbType.StringFixedLength:
case DbType.Xml:
if (!(parameter.Value is DBNull) && parameter.Value is string)
{
parameter.Value = Convert.ToString(parameter.Value, CultureInfo.InvariantCulture).ApplyCorrect();
}
break;
}
}
}
}
And in ApplyCorrect
method I call the HtmlSanitizer as follow:
public static string ApplyCorrect(this string input)
{
string sanitizedInput = string.Empty;
if (!string.IsNullOrEmpty(input))
{
var sanitizer = new HtmlSanitizer();
sanitizedInput = sanitizer.Sanitize(input);
}
return sanitizedInput;
}
I recommend that do not use Regular Expressions (Regex) to validate HTML according to the best practices. I would suggest the following library mganss/HtmlSanitizer which is an active library and updated regularly which you also mentioned in your question.