【问题标题】:How to use localization with data annotation in a separate DTO Assembly (Asp.net Core Web Api)如何在单独的 DTO 程序集中使用本地化和数据注释(Asp.net Core Web Api)
【发布时间】:2021-10-19 13:12:01
【问题描述】:

我有:

  • Dto.Library(.Net 5 库)
  • 带有 Resource.resx(.Net 5 库)的 SharedResourceLibrary

如何在我的 DTO.Library 中将资源文件消息与数据注释结合使用?

ErrorMessage 应该是 resx 文件中的文本:

public class MeterForCreationDto
{
    [Required(ErrorMessage = "Name must not be empty!")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Unit must not be empty!")]
    public string Unit { get; set; }
}

SharedResourceLibrary:looks like this answer @Shiran Dror

【问题讨论】:

    标签: c# asp.net-core-webapi


    【解决方案1】:

    您可以为属性创建自定义属性。像这样的:

    public class LocalizedDisplayNameAttribute: DisplayNameAttribute
    {
        public LocalizedDisplayNameAttribute(string resourceKey) 
            : base(GetMessageFromResource(resourceId))
        { }
    
        private static string GetMessageFromResource(string resourceKey)
        {
            // return the translation out of your .rsx files
        }
    }
    

    然后你需要添加

    public class MeterForCreationDto
    {
        [LocalizedDisplayName("Name")]
        public string Name { get; set; }
    
        [LocalizedDisplayName("Unit")]
        public string Unit { get; set; }
    }
    

    但您需要在 .rsx 文件中的属性中添加完全相同的键。如果您搜索“asp.net 本地化显示名称”,则会有很多不同的站点提供示例。

    创建自定义属性的一些帮助: https://docs.microsoft.com/en-gb/dotnet/standard/attributes/writing-custom-attributes

    希望对您有所帮助。 :)

    【讨论】:

    • 您好 NiceBone,非常感谢您的回答。但我真的不想每次都创建一个新属性。如果需要这样做,那么我更喜欢使用 fluent.validation 然后在验证过程中注入 IStringLocalizer 。我看到 ppls 使用 services.AddMVC().AddLocalization()。但这不适用于 web api。
    • 不幸的是,除了我上面描述的方法,我不能告诉你更多。到目前为止,我已经使用属性“LocalizedDisplayName”完成了所有工作。也许其他人有解决方案:)
    猜你喜欢
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2016-06-26
    • 2021-12-20
    • 2017-07-18
    • 1970-01-01
    相关资源
    最近更新 更多