最近在研究系统本地化的问题,不可避免要实现模型类的验证消息本地化。毕竟这些错误消息是要返回给用户的。
疑问产生
在mvc模型下,我们会使用模型类对请求参数进行绑定和验证。举个例子:
public class userdto { [required(errormessage = "姓名不能为空")] public string name{get; set;} [required(errormessage = "年龄不能为空")] [range(1, 120, errormessage = "年龄必须在1到120之间")] public int? age {get; set; } }
这样本身没有什么问题,但如果有大量模型要做本地化改造,那可就是个大工程了。
我们不禁要问,为什么要指定errormessage,默认的错误消息不能用吗?毕竟我们人工指定的错误消息除了字段名之外,其它都完全一样,实在没有必要逐个指定。
默认消息
我们来改造一下看看,删除掉指定的errormessage。
public class userdto { [required] public string name{get; set;} [required] [range(1, 120)] public int? age {get; set; } }
如果没有传入参数导致验证不通过,会得到如下消息:
"the name field is required."
"the age field is required."
没错,默认消息是英文的,这对我们来说完全不可用——这对用户很不友好,难怪要人工设置errormessage。
查找默认消息
那有没有可能直接把默认消息本地化呢?如果可以,那就不用再麻烦地设置errormessage了。
通过查看官方源码我们发现,默认消息来自sr类,以requiredattribute举例:
public requiredattribute() : base(() => sr.requiredattribute_validationerror) { }
sr类的内容简略如下:
internal static partial class sr { internal static global::system.resources.resourcemanager resourcemanager => s_resourcemanager ?? (s_resourcemanager = new global::system.resources.resourcemanager(typeof(fxresources.system.componentmodel.annotations.sr))); internal static string @requiredattribute_validationerror => getresourcestring("requiredattribute_validationerror", @"the {0} field is required."); }
上面的代码中,getresourcestring最终会调用内部声明的resourcemanager。而 resourcemanager会根据传入的类型参数查找本地化资源。
本地化默认消息
通过上面的分析,如果要使用中文内容,我们只要把本地化的消息放入fxresources.system.componentmodel.annotations.sr.zh-cn.resources 即可。动手之前,我们再确认一下。
ilspy 打开 system.componentmodel.annotations.dll,确实可以看到默认的资源fxresources.system.componentmodel.annotations.sr.resources,证明我们的分析没错。
默认(中立语言)资源里面包含了错误消息,也包含了内部的异常消息。我们可以全部或者选择地本地化它们。
建立语言扩展包
我们建立一个项目,名为 fxresources.system.componentmodel.annotations。根据默认规则,在项目中建立的资源会自动添加命名空间作为前缀。
因此我们只需要再创建名为 sr的资源即可。
如图,我们建立了对应的中文简体和中文繁体资源,这样就大功告成了!
说明:zh-hans兼容zh-cn、zh-sg;zh-hant兼容zh-tw、zh-mo、zh-hk。严格讲港澳台繁体略有差异,但在一般场景可以忽略。
最终效果
同样是之前的例子,我们不需要再指定errormessage。
public class userdto { [required] public string name{get; set;} [required] [range(1, 120)] public int? age {get; set; } }
现在我们得到的消息是这样,看起来还不错。
"name 字段为必填项。"
"age 字段为必填项。"
注意:如果你的项目没有启用国际化功能,你需要设置默认的文化为中文:cultureinfo.defaultthreaduiculture = cultureinfo.getcultureinfo("zh-hans")
nuget包
为方便大家使用,已经将语言资源打包为语言包,大家直接安装到项目即可。
install-package fxresources.system.componentmodel.annotations.zh-hans -version 9.0.0
.net 不同版本的资源之间有略微差异,大家选择对应的版本安装即可。
到此这篇关于asp.net core 模型验证消息的本地化新姿势的文章就介绍到这了,更多相关asp.net core 模型验证消息内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论