[英]How to use localization with data annotation in a separate DTO Assembly (Asp.net Core Web Api)
我有:
我如何在我的 DTO.Library 中將資源文件消息與數據注釋結合使用?
ErrorMessage 應該是 resx 文件中的文本:
public class MeterForCreationDto
{
[Required(ErrorMessage = "Name must not be empty!")]
public string Name { get; set; }
[Required(ErrorMessage = "Unit must not be empty!")]
public string Unit { get; set; }
}
SharedResourceLibrary: 看起來像這個答案@Shiran Dror
您可以為屬性創建自定義屬性。 像這樣:
public class LocalizedDisplayNameAttribute: DisplayNameAttribute
{
public LocalizedDisplayNameAttribute(string resourceKey)
: base(GetMessageFromResource(resourceId))
{ }
private static string GetMessageFromResource(string resourceKey)
{
// return the translation out of your .rsx files
}
}
然后你需要添加
public class MeterForCreationDto
{
[LocalizedDisplayName("Name")]
public string Name { get; set; }
[LocalizedDisplayName("Unit")]
public string Unit { get; set; }
}
但是您需要在 .rsx 文件中的屬性中添加完全相同的鍵。 如果您搜索“asp.net localizeddisplayname”,則有很多不同的站點提供示例。
創建自定義屬性的一些幫助: https://learn.microsoft.com/en-gb/do.net/standard/attributes/writing-custom-attributes
希望它有所幫助。 :)
您可以使用:
[Required(ErrorMessageResourceName ="NameInRecourseFile",ErrorMessageResourceType =typeof(RecourseFileName))]
您還需要從此菜單公開 Recourse 文件:
最后你需要有一個默認的資源文件[為你的默認文化]
默認資源文件名不應該有任何特定的文化 (.en,fr,....)
SharedService.en.resx => SharedService.resx
note.en 是您應用中的默認文化
所以它會喜歡這些:
SharedService.resx
[針對您的默認文化]
SharedService.ar.resx
SharedService.fr.resx
希望這對你有幫助。
最好的祝願。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.