在 ASP.net core mvc 3.1 中的 HtmlHelper 的扩展方法中使用 DataAnnotation localizer

Using DataAnnotation localizer in your extension method for HtmlHelper in ASP.net core mvc 3.1

我希望对 HTML Helper 进行扩展,以显示我的 ViewModel 属性 的描述。这里是清单,因为自从 How do I display the DisplayAttribute.Description attribute value? 以来,ASP.NET Core 3.1.

中的内容发生了变化

这是我的扩展方法:

public static string DescriptionFor<TModel, TValue>(this IHtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression) {
    MemberExpression memberExpression = (MemberExpression)expression.Body;
    var displayAttribute = (DisplayAttribute)memberExpression.Member.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault();
    string description = displayAttribute?.Description ?? memberExpression.Member?.Name;
    //But how can i localize this description
    return description;
}

但现在我需要将其本地化,例如

@Html.DisplayNameFor(model => model.MyNotObviousProperty)

如何在我的扩展方法中检索 DataAnnotationLocalizer?当然,我可以像传递参数一样传递它,但它不是很好的解决方案,当 DisplayNameFor 不要求额外的参数时。

您只需要获得对 IStringLocalizer 的引用。

在您的启动中:

public void Configure(..., IStringLocalizer stringLocalizer) // ASP.NET Core will inject it for you
{
    // your current code
    YourExtensionsClass.RegisterLocalizer(stringLocalizer);
}

在你的扩展中 class:

public static class YourExtensionsClass
{
    private static IStringLocalizer _localizer;

    public static void RegisterLocalizer(IStringLocalizer localizer)
    {
        _localizer = localizer;
    }

    public static string DescriptionFor<TModel, TValue>(this IHtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression) 
    {
        MemberExpression memberExpression = (MemberExpression)expression.Body;
        var displayAttribute = (DisplayAttribute)memberExpression.Member.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault();
        string description = displayAttribute?.Description ?? memberExpression.Member?.Name;
        
        return _localizer[description];
    }
}

如果你想要更多的控制权,我建议你从 ASP.NET Core 的内部运作方式中获得一些想法,by taking a look at the source code (method CreateDisplayMetadata)