[return: System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute("str")]
public static string? UrlPathEncode(string? str) { throw null; }
}
+ public partial interface IHtmlString
+ {
+ string ToHtmlString();
+ }
}
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
</PropertyGroup>
<ItemGroup>
+ <Compile Include="System\Web\IHtmlString.cs" />
<Compile Include="System\Web\HttpUtility.cs" />
<Compile Include="System\Web\Util\HttpEncoder.cs" />
<Compile Include="System\Web\Util\HttpEncoderUtility.cs" />
[return: NotNullIfNotNull(nameof(value))]
public static string? HtmlEncode(object? value) =>
- value == null ? null : HtmlEncode(Convert.ToString(value, CultureInfo.CurrentCulture) ?? string.Empty);
+ value switch
+ {
+ null => null,
+ IHtmlString ihs => ihs.ToHtmlString() ?? string.Empty,
+ _ => HtmlEncode(Convert.ToString(value, CultureInfo.CurrentCulture) ?? string.Empty),
+ };
public static void HtmlEncode(string? s, TextWriter output) => HttpEncoder.HtmlEncode(s, output);
--- /dev/null
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+namespace System.Web
+{
+ /// <summary>Represents an HTML-encoded string that should not be encoded again.</summary>
+ public interface IHtmlString
+ {
+ /// <summary>Returns an HTML-encoded string.</summary>
+ /// <returns>An HTML-encoded string.</returns>
+ string ToHtmlString();
+ }
+}
});
}
+ [Fact]
+ public void HtmlEncode_IHtmlString_UseToHtmlString()
+ {
+ Assert.Equal(string.Empty, HttpUtility.HtmlEncode(new ActionHtmlString(() => null)));
+ Assert.Equal(string.Empty, HttpUtility.HtmlEncode(new ActionHtmlString(() => string.Empty)));
+ Assert.Equal("<", HttpUtility.HtmlEncode(new ActionHtmlString(() => "<")));
+ Assert.Throws<FormatException>(() => HttpUtility.HtmlEncode(new ActionHtmlString(() => throw new FormatException())));
+ }
+
+ private sealed class ActionHtmlString(Func<string> toHtmlString) : IHtmlString
+ {
+ public string ToHtmlString() => toHtmlString();
+ }
+
#endregion HtmlEncode
#region JavaScriptStringEncode