iT邦幫忙

0

C# localization ModelState跨國語言

ksg 2019-02-11 23:36:28182 瀏覽

我繼承ValidationAttribute,做了一個custom的validation,
但我想在回傳錯誤的時候加入跨國語言localization,請問還有什麼辦法呢?
有嘗試了以下的方式,但是這樣是不可行的,再Model使用SearchItem的部分會出錯.
感謝.

public class SearchItemAttribute : ValidationAttribute
{
    private readonly IStringLocalizer<SharedResource> _sharedResource;
    public SearchItemAttribute(IStringLocalizer<SharedResource> sharedResource){
        _sharedResource = sharedResource;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var search = value as IDictionary<string, string>;
        
        if(search == null)
        {
            return new ValidationResult(_sharedResource["Search string must exist"]);
        }
        return ValidationResult.Success;
    }
}

Models
[SearchItem]
public IDictionary<string, string> search { get; set; }
暐翰 iT邦大師 1 級 ‧ 2019-02-12 21:22:43 檢舉
報甚麼錯誤訊息呢?
ksg iT邦新手 5 級 ‧ 2019-02-14 21:00:52 檢舉
抱歉晚回覆了,問題解決了喔.
使用validationContext裏頭的GetService就可以了
validationContext.GetService(typeof(IStringLocalizer<SharedResource>)) as IStringLocalizer<SharedResource>;

尚未有邦友回答

立即登入回答