[英]How to use localization with data annotation in a separate DTO Assembly (Asp.net Core Web Api)
I have:我有:
How can i use the Resource File Messages in conjunction with Data Annotation in my DTO.Library?我如何在我的 DTO.Library 中将资源文件消息与数据注释结合使用?
The ErrorMessage should be the text from the resx files: 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: looks like this answer @Shiran Dror SharedResourceLibrary: 看起来像这个答案@Shiran Dror
You can create a custom attribute for the properties.您可以为属性创建自定义属性。 Something like this:
像这样:
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
}
}
and then you need to add然后你需要添加
public class MeterForCreationDto
{
[LocalizedDisplayName("Name")]
public string Name { get; set; }
[LocalizedDisplayName("Unit")]
public string Unit { get; set; }
}
but you need to add exactly the same key in the attribute which is in your.rsx file.但是您需要在 .rsx 文件中的属性中添加完全相同的键。 If your searching for "asp.net localizeddisplayname" there are a lot of different sites with examples.
如果您搜索“asp.net localizeddisplayname”,则有很多不同的站点提供示例。
Some help for creating custom attributes: https://learn.microsoft.com/en-gb/do.net/standard/attributes/writing-custom-attributes创建自定义属性的一些帮助: https://learn.microsoft.com/en-gb/do.net/standard/attributes/writing-custom-attributes
Hopefully, it helps.希望它有所帮助。 :)
:)
you can use:您可以使用:
[Required(ErrorMessageResourceName ="NameInRecourseFile",ErrorMessageResourceType =typeof(RecourseFileName))]
also u need to make the Recourse file public from this menu:您还需要从此菜单公开 Recourse 文件:
finally u need to have a default Resource file[for your default culture]最后你需要有一个默认的资源文件[为你的默认文化]
Default resource file name shouldn't have any specific culture (.en،.fr،....)默认资源文件名不应该有任何特定的文化 (.en,fr,....)
SharedService.en.resx => SharedService.resx
note.en is the default culture in your app note.en 是您应用中的默认文化
so it will like these:所以它会喜欢这些:
SharedService.resx
[for your default culture] SharedService.resx
[针对您的默认文化]
SharedService.ar.resx
SharedService.fr.resx
Hope this helped you.希望这对你有帮助。
Best wishes.最好的祝愿。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.