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

Localization of data annotations using IStringLocalizer

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

    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; }
}

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

自定义属性

 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);

}

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

public class LocalizationService : IStringLocalizer {

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

//implement the rest of methods of IStringLocalizer 

}