[英]How to host an Angular app inside .NET Core 3.1 WebAPI?
[英]WebApi .net core 3.1 - How to customize validation message for null posting?
我有一個 class,它是 controller 中方法的參數,它具有必需的屬性(標記為 [Required])。
當我將 null 值傳遞給該屬性時,我收到一條消息:
"errors": {
"testNumber": [
"Error converting value {null} to type 'System.Int32'. Path 'testNumber', line 21, position 15."
]
}
同樣,當我將 null 值傳遞給該屬性時,我收到一條消息:
"errors": {
"testNumber": [
"JSON integer 999999999999999999999999999 is too large or small for an Int32. Path 'testNumber', line 21, position 38."
]
}
我想自定義友好消息說:
"errors": {
"testNumber": [
"null is not a valid value for TestNumber."
]
或者
"errors": {
"testNumber": [
"999999999999999999999999999 is not a valid value for TestNumber."
]
}
我的 TestClass 非常簡單:
public class TestClass
{
[Required]
public int TestNumber{ get; set; }
}
我看了一下他們建議使用的一些帖子:
[Required(ErrorMessage="<your value> is not a valid value for TestNumber.")]
public int TestNumber{ get; set; }
但是通過這種方式,我無法獲得客戶端發送的原始值。 那么是否可以像上面那樣自定義消息?
謝謝你。
所以它有點亂,但您可以為此使用 CustomAttributes。 你基本上是在重寫邏輯,但不是世界末日: https://learn.microsoft.com/en-us/as.net/core/mvc/models/validation?view=as.netcore-6.0#custom -屬性
這樣就可以執行你想做的事情了。 如果你不喜歡它的聲音,你可能想看看在 .NET Core 中編寫中間件或過濾器:
https://learn.microsoft.com/en-us/as.net/core/mvc/controllers/filters?view=as.netcore-6.0
https://learn.microsoft.com/en-us/as.net/core/fundamentals/middleware/?view=as.netcore-6.0
比我更有學問的人可能會告訴你如何以一種很好的方式將它們組合在一起(我不知道),但你實際上是用你自己的方式替換內置的 .NET 核心驗證邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.