c# - 使用 IStringLocalizer 对数据注释进行本地化

标签 c# asp.net-core asp.net-core-mvc data-annotations asp.net-core-1.0

我尝试使用 IStringLocalizer 在 .net core 1.0 应用程序中实现本地化。我能够为我编写了类似内容的 View 进行本地化

    private readonly IStringLocalizer<AboutController> _localizer;

    public AboutController(IStringLocalizer<AboutController> localizer)
    {
        _localizer = localizer;
    }

    public IActionResult About()
    {
        ViewBag.Name = _localizer["Name"];
        Return View();
    }

所以这工作正常,但我很好奇如何在 CustomAttribute 中使用 IStringLocalizer,我将从那里获取本地化验证消息。

型号

public partial class LMS_User
{
    [RequiredFieldValidator("FirstNameRequired")]
    public string FirstName { get; set; }

    [RequiredFieldValidator("LastNameRequired")]
    public string LastName { get; set; }
}

我已从模型中将资源 key 传递给自定义属性,我将在其中检索本地化消息。

自定义属性

 public class RequiredFieldValidator: ValidationAttribute , IClientModelValidator
    {
private readonly string resourcekey = string.Empty;        
public RequiredFieldValidator(string resourceID)
    {
        resourcekey = resourceID;
    }
}

public void AddValidation(ClientModelValidationContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        // Here I want to get localized message using SQL.
        var errorMessage = "This field is required field.";
        MergeAttribute(context.Attributes, "data-val", "true");
        MergeAttribute(context.Attributes, "data- val-Required",errorMessage);

}

private static bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }
        attributes.Add(key, value);
        return true;
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        return ValidationResult.Success;
    }

那么,如何在自定义属性中使用 IStringLocalizer 呢?我想使用 SQL 执行此操作。

对此表示赞赏的任何帮助!

最佳答案

我喜欢将本地化作为一项服务来实现。

public RequiredFieldValidator(IStringLocalizer localizationService, string resourceID)
    {
        resourcekey = resourceID;
        localization = localizationService;
    }

public void AddValidation(ClientModelValidationContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        // Here I want to get localized message using SQL.
        var errorMessage = lozalization["requiredFieldMessage"];
        MergeAttribute(context.Attributes, "data-val", "true");
        MergeAttribute(context.Attributes, "data- val-Required",errorMessage);

}

您可以选择使用资源字符串实现接口(interface),访问数据库以获取翻译,...这里我正在实现一种访问资源字符串的方法,假设资源在同一个项目中。

public class LocalizationService : IStringLocalizer {

  public LocalizedString this[string name] {
    return new LocalizedString(name, Properties.Resources.GetString(name));
  }

//implement the rest of methods of IStringLocalizer 

}

关于c# - 使用 IStringLocalizer 对数据注释进行本地化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39144569/

相关文章:

asp.net-core-mvc - EF7 和 GroupBy() 无法翻译

c# - ASP.NET Core EF - 上传文件时出错

asp.net-core - 如何在 ASP.NET Core 应用程序中正确处理 Serilog 2.0?

c# - 带有 WellKnownText 空间数据列的 SqlBulkCopy DataTable

c# - Assert.DoesNotThrow with NUnit——如何获取堆栈跟踪?

asp.net-core - IdentityServer4: [Authorize(Roles = "Admin")] 即使 JWT token 具有 {"role": "Admin"} 声明,也不授予管理员用户访问权限

asp.net-core-mvc - Asp.Net Core MVC - 我可以将 Identity 和 DataAccess 移到类库吗

azure - Azure 上的架构更新 : Column name does not exist

c# - 读取 DTD 或 Schema 并列出给定元素的所有有效子元素或属性

c# - 为什么 32 位首选标志甚至存在?