ASP.NET 核心 TagHelper 属性的默认值

Default Values for ASP.NET Core TagHelper Properties

如果我有以下标签助手:

[Flags]
public enum SubresourceIntegrityHashAlgorithm
{
    SHA256 = 1,
    SHA384 = 2,
    SHA512 = 4
}  

[HtmlTargetElement("script", Attributes = "asp-subresource-integrity")]
public class FooTagHelper : TagHelper
{
    [HtmlAttributeName("asp-subresource-integrity")]
    public SubresourceIntegrityHashAlgorithm HashAlgorithms { get; set; } 
        = SubresourceIntegrityHashAlgorithm.SHA256;

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        // ...
    }
}

如何使用我在上面 属性 中给出的默认值,以便在使用时不必为 属性 提供值:

<script asp-subresource-integrity src="..."></script>

而不是:

<script asp-subresource-integrity="SubresourceIntegrityHashAlgorithm.SHA256" src="..."></script>

更新

我在 MVC GitHub 页面 here 上提出了一个问题,因为这应该是一个内置功能。

当您将属性添加到 HtmlTargetElement 的属性列表时,该属性是要应用的标签助手所必需的,并且它需要一个值。

如果您尝试在没有值或空值的情况下使用它,您将收到如下错误:

<my-script asp-subresource-integrity src="foo.js"></my-script>

Tag helper bound attributes of type 'WebApplication7.TagHelpers.SubresourceIntegrityHashAlgorithm' cannot be empty or contain only whitespace

即使将属性的类型更改为可空类型,如字符串,也会得到相同的错误。到目前为止,我发现的拥有可选属性的最佳方法是不将它们包含在属性列表中:

[HtmlTargetElement("script")]

当然,这意味着无论是否存在 asp-subresource-integrity 属性,您的标签助手都会被应用,而您很可能不希望这样。有几种方法可以解决这个问题:

  • 您可以使用另一个属性作为 "marker" 属性,这除了限制您的标签助手在 marker 属性存在时应用之外没有任何作用。

    [HtmlTargetElement("script", Attributes = "my-script")]
    public class FooScriptTagHelper : TagHelper
    {
        ...
    }
    
    <!--This uses the default value-->
    <script my-script src="foo.js"></script>
    <!--This uses a specific value-->
    <script my-script asp-subresource-integrity="..." src="foo.js"></script>
    
  • 替代方法是使用自定义标签名称,然后您可以在使用默认值时省略该属性:

    [HtmlTargetElement("my-script")]
    
    <!--This uses the default value-->
    <my-script src="foo.js"></my-script>
    <!--This uses a specific value-->
    <my-script asp-subresource-integrity="..." src="foo.js"></my-script>
    

请记住,即使使用这些方法,当您使用该属性时,您仍然需要提供一个值。我的意思是,您可以添加或省略该属性,但如果该属性存在,则它需要一个非空值:

<!--This will still throw an exception-->
<my-script asp-subresource-integrity src="foo.js"></my-script>