You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core(.NET 5)中GetUnobtrusiveValidationAttributes的等效方法是什么

ASP.NET Core 5 实现等效非侵入式验证属性获取的方案

ASP.NET Core MVC 中已经将原 HtmlHelper.GetUnobtrusiveValidationAttributes 的功能迁移到了 IHtmlGenerator 服务中,你可以按以下方式实现完全等效的效果:


实现步骤

  • 首先获取 IHtmlGenerator 服务实例,在自定义 Html 扩展方法中可以直接从当前请求的服务容器获取,在 TagHelper 中可以通过构造函数直接注入。
  • 调用 IHtmlGenerator.GetValidationAttributes 方法即可拿到和原生方法完全一致的非侵入式验证属性集合。

代码示例

自定义Html扩展方法场景

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.DependencyInjection;

public static class CustomHtmlExtensions
{
    public static TagBuilder BuildCustomInput(this IHtmlHelper htmlHelper, string name, ModelMetadata metadata)
    {
        var tagBuilder = new TagBuilder("input");
        // 获取非侵入式验证属性
        var htmlGenerator = htmlHelper.ViewContext.HttpContext.RequestServices
            .GetRequiredService<IHtmlGenerator>();
        var validationAttrs = htmlGenerator.GetValidationAttributes(
            htmlHelper.ViewContext, 
            metadata, 
            name
        );
        // 合并属性,和原用法完全兼容
        tagBuilder.MergeAttributes(validationAttrs);
        
        // 其余自定义逻辑
        return tagBuilder;
    }
}

自定义TagHelper场景

using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;

[HtmlTargetElement("custom-input")]
public class CustomInputTagHelper : TagHelper
{
    private readonly IHtmlGenerator _htmlGenerator;

    // 构造函数注入IHtmlGenerator
    public CustomInputTagHelper(IHtmlGenerator htmlGenerator)
    {
        _htmlGenerator = htmlGenerator;
    }

    [HtmlAttributeName("asp-for")]
    public ModelExpression For { get; set; }

    [ViewContext]
    [HtmlAttributeNotBound]
    public ViewContext ViewContext { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "input";
        // 获取验证属性
        var validationAttrs = _htmlGenerator.GetValidationAttributes(
            ViewContext, 
            For.Metadata, 
            For.Name
        );
        output.MergeAttributes(validationAttrs);
    }
}

注意事项

  • GetValidationAttributes 直接返回 IDictionary<string, object> 类型,可直接传入 MergeAttributes 方法,和原有逻辑完全兼容。
  • 只要项目保持默认的客户端验证开启配置(MvcOptions.HtmlHelperOptions.ClientValidationEnabled = true),返回的验证属性和 .NET Framework 中的输出完全一致。

内容的提问来源于stack exchange,提问作者inthegarden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 11:33:01