使用IStringLocalizer本地化数据注释

时间:2016-08-25 11:52:31

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

我尝试使用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做到这一点。

对此appreaciated的任何帮助!

1 个答案:

答案 0 :(得分:2)

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

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 

}