如何本地化.NET API中的’X字段是必需的’本地错误?

huangapple go评论64阅读模式
英文:

How to localize 'The X field is required' native error in .NET API?

问题

我正在从我的API构建自定义验证响应,并进行本地化。我需要本地化在请求API时绑定模型变量的默认错误消息。我已经本地化了几乎所有内容,但仍然会收到The X field is required的英文错误消息。

我使用了来自此回答的解决方案,它在.NET 7中运行良好,但此选项配置器缺少The X field is required的消息。

我还找到了使用[Required]属性并覆盖其消息的解决方案,但应用程序处于高级状态,因此这将需要很多时间。

英文:

I'm building custom validation response from my API with localization. I need to localize default error messages for variables on model binding when requesting API. I localized almost everything, but I still get The X field is required in English.

I used solution from this response and it works well with .NET 7, however this options configurator misses message for The X field is required.

I also found solution with adding [Required] attribute and overriding its message, but application is in advanced state, so this would take a lot of time.

答案1

得分: 1

在使用FluentValidation时,您可以定义规则如下:
RuleFor(v => v.Item) .NotNull() .WithMessage("'Item' 不能为空。");

英文:

When using FluentValidation you can define the rules as follows:
RuleFor(v => v.Item)
.NotNull()
.WithMessage("'Item' cannot be null.");

Provide the localization inside the WithMessage().

答案2

得分: 0

"Why not using FluentValidation docs.fluentvalidation.net/en/latest/aspnet.html"

英文:

why not using fluentvalidation docs.fluentvalidation.net/en/latest/aspnet.html

huangapple
  • 本文由 发表于 2023年5月21日 06:10:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297534.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定