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

ASP.NET MVC迁移至ASP.NET Core 6.0:自定义元数据提供程序等效实现

ASP.NET Core 6.0中等效实现方案

1. 调整自定义ModelMetadataProvider实现

ASP.NET Core 6.0中,DataAnnotationsModelMetadataProvider的CreateMetadata方法签名有变化:移除了Func<object> modelAccessor参数,属性集合类型从IEnumerable<Attribute>改为IEnumerable<object>。调整后的代码如下:

using Microsoft.AspNetCore.Mvc.ModelMetadata;
using System.ComponentModel.DataAnnotations;
using System.Linq;

public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(
        IEnumerable<object> attributes,
        Type containerType,
        Type modelType,
        string propertyName)
    {
        var metadata = base.CreateMetadata(attributes, containerType, modelType, propertyName);

        var textAreaAttribute = attributes.OfType<TextAreaAttribute>().FirstOrDefault();
        if (textAreaAttribute != null)
        {
            metadata.AdditionalValues["TextArea"] = null;
            metadata.AdditionalValues["Rows"] = textAreaAttribute.Rows;
            metadata.AdditionalValues["Columns"] = textAreaAttribute.Columns;
            metadata.AdditionalValues["MaxLength"] = textAreaAttribute.MaxLength;
            metadata.AdditionalValues["Placeholder"] = textAreaAttribute.Placeholder;
        }

        var textInputAttribute = attributes.OfType<TextInputAttribute>().FirstOrDefault();
        if (textInputAttribute != null)
        {
            metadata.AdditionalValues["TextInput"] = null;
            metadata.AdditionalValues["MaxLength"] = textInputAttribute.MaxLength;
        }

        return metadata;
    }
}

这里用OfType<T>()替代了原有的类型判断逻辑,代码更简洁直观。

2. 保留TextInputAttribute定义

原TextInputAttribute无需修改,可直接沿用:

public class TextInputAttribute : Attribute
{
    public int MaxLength { get; set; }

    public Dictionary<string, object> OptionalAttributes()
    {
        return new Dictionary<string, object>
        {
            { "MaxLength", MaxLength }
        };
    }
}

使用方式和原项目一致:

[TextInput(MaxLength = 10)] // 限制输入字符数为10

3. 注册自定义ModelMetadataProvider

在ASP.NET Core 6.0的Program.cs中,通过依赖注入容器注册自定义元数据提供器,替换默认实现:

var builder = WebApplication.CreateBuilder(args);

// 注册自定义ModelMetadataProvider
builder.Services.AddSingleton<IModelMetadataProvider, CustomModelMetadataProvider>();

// 其他服务配置
builder.Services.AddControllersWithViews();

var app = builder.Build();

// 中间件配置
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

完成以上配置后,ASP.NET Core会自动使用你的自定义元数据提供器处理模型元数据。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:27:34