20240311-1
This commit is contained in:
parent
2a66cf7b61
commit
66b5f5741b
@ -1,207 +1,208 @@
|
||||
using anbs_cp.ForNet.Enums;
|
||||
|
||||
using Ganss.Xss;
|
||||
|
||||
namespace anbs_cp.ForNet.Classes;
|
||||
|
||||
/// <summary>
|
||||
/// Очистка текста от лишних HTML-тегов
|
||||
/// Очистка текста от лишних HTML-тегов
|
||||
/// </summary>
|
||||
public static class Sanitizer
|
||||
{
|
||||
#region Свойства
|
||||
#region Свойства
|
||||
|
||||
/// <summary>
|
||||
/// Все теги запрещены
|
||||
/// </summary>
|
||||
public static SanitizerAllowedHtml AllowedNone => GetNone();
|
||||
/// <summary>
|
||||
/// Все теги запрещены
|
||||
/// </summary>
|
||||
public static SanitizerAllowedHtml AllowedNone => GetNone();
|
||||
|
||||
/// <summary>
|
||||
/// Все теги разрешены
|
||||
/// </summary>
|
||||
public static SanitizerAllowedHtml AllowedAll => GetAll();
|
||||
/// <summary>
|
||||
/// Все теги разрешены
|
||||
/// </summary>
|
||||
public static SanitizerAllowedHtml AllowedAll => GetAll();
|
||||
|
||||
/// <summary>
|
||||
/// Оставлены только текстовые теги
|
||||
/// </summary>
|
||||
public static SanitizerAllowedHtml AllowedTextOnly => GetTextFormatOnly();
|
||||
/// <summary>
|
||||
/// Оставлены только текстовые теги
|
||||
/// </summary>
|
||||
public static SanitizerAllowedHtml AllowedTextOnly => GetTextFormatOnly();
|
||||
|
||||
/// <summary>
|
||||
/// Оставлены только текстовые теги, а также img и a
|
||||
/// </summary>
|
||||
public static SanitizerAllowedHtml AllowedImageAndLinks => GetImageAndLinks();
|
||||
/// <summary>
|
||||
/// Оставлены только текстовые теги, а также img и a
|
||||
/// </summary>
|
||||
public static SanitizerAllowedHtml AllowedImageAndLinks => GetImageAndLinks();
|
||||
|
||||
/// <summary>
|
||||
/// Применяются все теги, кроме iframe
|
||||
/// </summary>
|
||||
public static SanitizerAllowedHtml AllowedAllExceptIFrame => GetAllExceptIFrame();
|
||||
/// <summary>
|
||||
/// Применяются все теги, кроме iframe
|
||||
/// </summary>
|
||||
public static SanitizerAllowedHtml AllowedAllExceptIFrame => GetAllExceptIFrame();
|
||||
|
||||
#endregion
|
||||
#endregion
|
||||
|
||||
#region Методы
|
||||
#region Методы
|
||||
|
||||
/// <summary>
|
||||
/// Очистка html-кода <paramref name="html"/> согласно параметрам <paramref name="allowedHtml"/>
|
||||
/// </summary>
|
||||
/// <param name="html">HTML-код</param>
|
||||
/// <param name="allowedHtml">Параметры очистки</param>
|
||||
/// <returns>Очищенный html-кода</returns>
|
||||
private static string SanitizeHtml(string html, SanitizerAllowedHtml allowedHtml)
|
||||
/// <summary>
|
||||
/// Очистка html-кода <paramref name="html" /> согласно параметрам <paramref name="allowedHtml" />
|
||||
/// </summary>
|
||||
/// <param name="html">HTML-код</param>
|
||||
/// <param name="allowedHtml">Параметры очистки</param>
|
||||
/// <returns>Очищенный html-кода</returns>
|
||||
public static string SanitizeHtml (string html, SanitizerAllowedHtml allowedHtml)
|
||||
{
|
||||
// Создаю очиститель
|
||||
HtmlSanitizer sanitizer = new()
|
||||
{
|
||||
// Создаю очиститель
|
||||
HtmlSanitizer sanitizer = new()
|
||||
{
|
||||
// - сохраняю дочерние удалённых
|
||||
KeepChildNodes = true
|
||||
};
|
||||
// - сохраняю дочерние удалённых
|
||||
KeepChildNodes = true
|
||||
};
|
||||
|
||||
// Выключаю все параметры HTML
|
||||
sanitizer.AllowedTags.Clear();
|
||||
sanitizer.AllowedSchemes.Clear();
|
||||
sanitizer.AllowedCssProperties.Clear();
|
||||
sanitizer.AllowedClasses.Clear();
|
||||
sanitizer.AllowedAttributes.Clear();
|
||||
sanitizer.AllowedAtRules.Clear();
|
||||
sanitizer.AllowDataAttributes = false;
|
||||
// Выключаю все параметры HTML
|
||||
sanitizer.AllowedTags.Clear();
|
||||
sanitizer.AllowedSchemes.Clear();
|
||||
sanitizer.AllowedCssProperties.Clear();
|
||||
sanitizer.AllowedClasses.Clear();
|
||||
sanitizer.AllowedAttributes.Clear();
|
||||
sanitizer.AllowedAtRules.Clear();
|
||||
sanitizer.AllowDataAttributes = false;
|
||||
|
||||
// Загружаю параметры
|
||||
sanitizer.AllowedTags.UnionWith(allowedHtml.AllowedTags);
|
||||
sanitizer.AllowedSchemes.UnionWith(allowedHtml.AllowedSchemes);
|
||||
sanitizer.AllowedCssProperties.UnionWith(allowedHtml.AllowedCssProperties);
|
||||
sanitizer.AllowedClasses.UnionWith(allowedHtml.AllowedClasses);
|
||||
sanitizer.AllowedAttributes.UnionWith(allowedHtml.AllowedAttributes);
|
||||
sanitizer.AllowDataAttributes = allowedHtml.AllowDataAttributes;
|
||||
// Загружаю параметры
|
||||
sanitizer.AllowedTags.UnionWith(allowedHtml.AllowedTags);
|
||||
sanitizer.AllowedSchemes.UnionWith(allowedHtml.AllowedSchemes);
|
||||
sanitizer.AllowedCssProperties.UnionWith(allowedHtml.AllowedCssProperties);
|
||||
sanitizer.AllowedClasses.UnionWith(allowedHtml.AllowedClasses);
|
||||
sanitizer.AllowedAttributes.UnionWith(allowedHtml.AllowedAttributes);
|
||||
sanitizer.AllowDataAttributes = allowedHtml.AllowDataAttributes;
|
||||
|
||||
// Очищаю html согласно правилам
|
||||
return sanitizer.Sanitize(html);
|
||||
}
|
||||
// Очищаю html согласно правилам
|
||||
return sanitizer.Sanitize(html);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Очистка html-кода по уровню очистки
|
||||
/// </summary>
|
||||
/// <param name="html">HTML-код</param>
|
||||
/// <param name="level">Уровень очистка</param>
|
||||
/// <returns>Очищенный html-код</returns>
|
||||
public static string SanitizeHtml(string html, ESanitizerLevel level)
|
||||
/// <summary>
|
||||
/// Очистка html-кода по уровню очистки
|
||||
/// </summary>
|
||||
/// <param name="html">HTML-код</param>
|
||||
/// <param name="level">Уровень очистка</param>
|
||||
/// <returns>Очищенный html-код</returns>
|
||||
public static string SanitizeHtml (string html, ESanitizerLevel level)
|
||||
{
|
||||
// Получаю параметры очистки
|
||||
SanitizerAllowedHtml allowedHtml = level switch
|
||||
{
|
||||
// Получаю параметры очистки
|
||||
SanitizerAllowedHtml allowedHtml = level switch
|
||||
{
|
||||
ESanitizerLevel.NoTags => AllowedNone,
|
||||
ESanitizerLevel.TextFormatOnly => AllowedTextOnly,
|
||||
ESanitizerLevel.ImageAndLinks => AllowedImageAndLinks,
|
||||
ESanitizerLevel.AllExceptIFrame => AllowedAllExceptIFrame,
|
||||
ESanitizerLevel.All => AllowedAll,
|
||||
var _ => AllowedAll
|
||||
};
|
||||
ESanitizerLevel.NoTags => AllowedNone,
|
||||
ESanitizerLevel.TextFormatOnly => AllowedTextOnly,
|
||||
ESanitizerLevel.ImageAndLinks => AllowedImageAndLinks,
|
||||
ESanitizerLevel.AllExceptIFrame => AllowedAllExceptIFrame,
|
||||
ESanitizerLevel.All => AllowedAll,
|
||||
var _ => AllowedAll
|
||||
};
|
||||
|
||||
// Очищаю код и возвращаю результат очистки
|
||||
return SanitizeHtml(html, allowedHtml);
|
||||
}
|
||||
// Очищаю код и возвращаю результат очистки
|
||||
return SanitizeHtml(html, allowedHtml);
|
||||
}
|
||||
|
||||
#endregion
|
||||
#endregion
|
||||
|
||||
#region Вспомогателдьные методы
|
||||
#region Вспомогателдьные методы
|
||||
|
||||
/// <summary>
|
||||
/// Получаю параметры, удаляющие все теги
|
||||
/// </summary>
|
||||
/// <returns>Параметры очистки</returns>
|
||||
private static SanitizerAllowedHtml GetNone() =>
|
||||
new()
|
||||
{
|
||||
AllowedTags = [],
|
||||
AllowedAttributes = [],
|
||||
AllowedCssProperties = [],
|
||||
AllowedClasses = [],
|
||||
AllowedSchemes = [],
|
||||
AllowDataAttributes = false
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Получаю параметры по умолчанию (разрешающие все теги)
|
||||
/// </summary>
|
||||
/// <returns>Параметры очистки</returns>
|
||||
private static SanitizerAllowedHtml GetAll()
|
||||
/// <summary>
|
||||
/// Получаю параметры, удаляющие все теги
|
||||
/// </summary>
|
||||
/// <returns>Параметры очистки</returns>
|
||||
private static SanitizerAllowedHtml GetNone () =>
|
||||
new()
|
||||
{
|
||||
// Создаю очиститель
|
||||
HtmlSanitizer sanitizer = new();
|
||||
AllowedTags = [],
|
||||
AllowedAttributes = [],
|
||||
AllowedCssProperties = [],
|
||||
AllowedClasses = [],
|
||||
AllowedSchemes = [],
|
||||
AllowDataAttributes = false
|
||||
};
|
||||
|
||||
// Создаю модель
|
||||
return new()
|
||||
{
|
||||
AllowedTags = sanitizer.AllowedTags.ToList(),
|
||||
AllowedAttributes = sanitizer.AllowedAttributes.ToList(),
|
||||
AllowedCssProperties = sanitizer.AllowedCssProperties.ToList(),
|
||||
AllowedClasses = sanitizer.AllowedClasses.ToList(),
|
||||
AllowedSchemes = sanitizer.AllowedSchemes.ToList(),
|
||||
AllowDataAttributes = true
|
||||
};
|
||||
}
|
||||
/// <summary>
|
||||
/// Получаю параметры по умолчанию (разрешающие все теги)
|
||||
/// </summary>
|
||||
/// <returns>Параметры очистки</returns>
|
||||
private static SanitizerAllowedHtml GetAll ()
|
||||
{
|
||||
// Создаю очиститель
|
||||
HtmlSanitizer sanitizer = new();
|
||||
|
||||
/// <summary>
|
||||
/// Параметры, оставляющие только текстовые теги
|
||||
/// </summary>
|
||||
/// <returns>Параметры очистки</returns>
|
||||
private static SanitizerAllowedHtml GetTextFormatOnly() =>
|
||||
new()
|
||||
{
|
||||
AllowedTags =
|
||||
[
|
||||
"strong", "b", "em", "i", "u", "hr", "strike", "div", "ol", "ul", "li", "p", "span", "h1", "h2", "h3",
|
||||
"h4"
|
||||
],
|
||||
|
||||
// ReSharper disable StringLiteralTypo
|
||||
AllowedAttributes =
|
||||
[
|
||||
"align", "bgcolor", "border", "cellpadding", "cellspacing", "charset", "checked", "class", "clear",
|
||||
"color",
|
||||
"cols", "colspan", "datetime", "disabled", "headers", "height", "high", "hspace", "label", "lang",
|
||||
"list",
|
||||
"low", "max", "maxlength", "min", "name", "nowrap", "placeholder", "required", "rev", "rows", "rowspan",
|
||||
"rules", "selected", "size", "span", "spellcheck", "style", "summary", "tabindex", "title", "type",
|
||||
"valign",
|
||||
"value", "vspace", "width", "wrap"
|
||||
]
|
||||
// ReSharper restore StringLiteralTypo
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Параметры, оставляющие только текстовые теги, а также img и a
|
||||
/// </summary>
|
||||
/// <returns>Параметры очистки</returns>
|
||||
private static SanitizerAllowedHtml GetImageAndLinks()
|
||||
// Создаю модель
|
||||
return new()
|
||||
{
|
||||
// Получаю текстовые параметры
|
||||
SanitizerAllowedHtml result = AllowedTextOnly;
|
||||
AllowedTags = sanitizer.AllowedTags.ToList(),
|
||||
AllowedAttributes = sanitizer.AllowedAttributes.ToList(),
|
||||
AllowedCssProperties = sanitizer.AllowedCssProperties.ToList(),
|
||||
AllowedClasses = sanitizer.AllowedClasses.ToList(),
|
||||
AllowedSchemes = sanitizer.AllowedSchemes.ToList(),
|
||||
AllowDataAttributes = true
|
||||
};
|
||||
}
|
||||
|
||||
// Добавляю теги
|
||||
result.AllowedTags.AddRange(["a", "img"]);
|
||||
|
||||
// Добавляю параметры
|
||||
// ReSharper disable StringLiteralTypo
|
||||
result.AllowedAttributes.AddRange(["alt", "href", "hreflang", "nohref", "rel", "src", "target"]);
|
||||
// ReSharper restore StringLiteralTypo
|
||||
|
||||
// Возвращаю результат
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Применяются все теги, кроме iframe
|
||||
/// </summary>
|
||||
/// <returns>Параметры очистки</returns>
|
||||
private static SanitizerAllowedHtml GetAllExceptIFrame()
|
||||
/// <summary>
|
||||
/// Параметры, оставляющие только текстовые теги
|
||||
/// </summary>
|
||||
/// <returns>Параметры очистки</returns>
|
||||
private static SanitizerAllowedHtml GetTextFormatOnly () =>
|
||||
new()
|
||||
{
|
||||
// Получаю все параметры
|
||||
SanitizerAllowedHtml result = AllowedAll;
|
||||
AllowedTags =
|
||||
[
|
||||
"strong", "b", "em", "i", "u", "hr", "strike", "div", "ol", "ul", "li", "p", "span", "h1", "h2", "h3",
|
||||
"h4"
|
||||
],
|
||||
|
||||
// Удаляю iframe
|
||||
result.AllowedTags.Remove("iframe");
|
||||
// ReSharper disable StringLiteralTypo
|
||||
AllowedAttributes =
|
||||
[
|
||||
"align", "bgcolor", "border", "cellpadding", "cellspacing", "charset", "checked", "class", "clear",
|
||||
"color",
|
||||
"cols", "colspan", "datetime", "disabled", "headers", "height", "high", "hspace", "label", "lang",
|
||||
"list",
|
||||
"low", "max", "maxlength", "min", "name", "nowrap", "placeholder", "required", "rev", "rows", "rowspan",
|
||||
"rules", "selected", "size", "span", "spellcheck", "style", "summary", "tabindex", "title", "type",
|
||||
"valign",
|
||||
"value", "vspace", "width", "wrap"
|
||||
]
|
||||
// ReSharper restore StringLiteralTypo
|
||||
};
|
||||
|
||||
// Возвращаю результат
|
||||
return result;
|
||||
}
|
||||
/// <summary>
|
||||
/// Параметры, оставляющие только текстовые теги, а также img и a
|
||||
/// </summary>
|
||||
/// <returns>Параметры очистки</returns>
|
||||
private static SanitizerAllowedHtml GetImageAndLinks ()
|
||||
{
|
||||
// Получаю текстовые параметры
|
||||
SanitizerAllowedHtml result = AllowedTextOnly;
|
||||
|
||||
#endregion
|
||||
// Добавляю теги
|
||||
result.AllowedTags.AddRange(["a", "img"]);
|
||||
|
||||
// Добавляю параметры
|
||||
// ReSharper disable StringLiteralTypo
|
||||
result.AllowedAttributes.AddRange(["alt", "href", "hreflang", "nohref", "rel", "src", "target"]);
|
||||
// ReSharper restore StringLiteralTypo
|
||||
|
||||
// Возвращаю результат
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Применяются все теги, кроме iframe
|
||||
/// </summary>
|
||||
/// <returns>Параметры очистки</returns>
|
||||
private static SanitizerAllowedHtml GetAllExceptIFrame ()
|
||||
{
|
||||
// Получаю все параметры
|
||||
SanitizerAllowedHtml result = AllowedAll;
|
||||
|
||||
// Удаляю iframe
|
||||
result.AllowedTags.Remove("iframe");
|
||||
|
||||
// Возвращаю результат
|
||||
return result;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
@ -6,7 +6,7 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
|
||||
<PackageId>ANBSoftware.ComponentsPackForNet</PackageId>
|
||||
<Version>2024.3.11.0</Version>
|
||||
<Version>2024.3.11.1</Version>
|
||||
<Authors>Александр Бабаев</Authors>
|
||||
<Product>Набор компонентов ANB Software для ASP.NET Core</Product>
|
||||
<Description>Библиотека полезных методов языка C# для ASP.NET Core</Description>
|
||||
|
Loading…
x
Reference in New Issue
Block a user