iT邦幫忙

0

C# 客製化的ValidationAttribute如何加入Localization

Ks 2019-02-11 23:36:28850 瀏覽
  • 分享至 

  • xImage

我客製化了一個ValidationAttribute,

但我想在回傳錯誤時,擁有Localization多國語言的信息

有嘗試了以下的方式,但是這樣是不可行的,再Model使用SearchItem的部分會出錯.
感謝.

【已解決】

public class TestAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var search = value as IDictionary<string, string>;
        
        var _sharedResource = validationContext.GetService(typeof(IStringLocalizer<SharedResource>)) as IStringLocalizer<SharedResource>;
        
        if(search == null)
        {
            return new ValidationResult(_sharedResource["string must exist"]);
        }
        return ValidationResult.Success;
    }
}

Models
[TestItem]
public IDictionary<string, string> test { get; set; }
暐翰 iT邦大師 1 級 ‧ 2019-02-12 21:22:43 檢舉
報甚麼錯誤訊息呢?
Ks iT邦新手 3 級 ‧ 2019-02-14 21:00:52 檢舉
抱歉晚回覆了,問題解決了喔,非常感謝
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
JamesDoge
iT邦高手 1 級 ‧ 2023-01-29 05:10:52

有嘗試了以下的方式,但是這樣是不可行的,再Model使用SearchItem的部分會出錯.

如果在Model中使用[TestItem]特性會出錯,那最有可能是因為在您的專案中缺少IStringLocalizer服務的設置。

請確保在Startup.cs類中的ConfigureServices方法中已經正確設置了IStringLocalizer服務。

services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddControllersWithViews().AddViewLocalization().AddDataAnnotationsLocalization();

您還需要確保您的SharedResource.resx檔案存在於您的Resources資料夾中。

我要發表回答

立即登入回答