简体   繁体   中英

WebApi .net core 3.1 - How to customize validation message for null posting?

I have a class which is a parameter of a method in controller which has a required property (mark as [Required]).

When I pass a null value to that property I get a message saying:

 "errors": {
    "testNumber": [
        "Error converting value {null} to type 'System.Int32'. Path 'testNumber', line 21, position 15."
    ]
}

Similarly, when I pass a null value to that property I get a message saying:

"errors": {
    "testNumber": [
        "JSON integer 999999999999999999999999999 is too large or small for an Int32. Path 'testNumber', line 21, position 38."
    ]
}

I want to customize the friendly messages saying:

"errors": {
    "testNumber": [
        "null is not a valid value for TestNumber."
]

or

"errors": {
    "testNumber": [
        "999999999999999999999999999 is not a valid value for TestNumber."
    ]
}

My TestClass is very simple:

public class TestClass
{
     [Required]
     public int TestNumber{ get; set; }
}

I have a look at some posts they suggest to use:

[Required(ErrorMessage="<your value> is not a valid value for TestNumber.")]
public int TestNumber{ get; set; }

But by doing this way, I can't get the original value sent from client. So is this possible to customize the messages like above?

Thank you.

So it's a bit messy but you can use CustomAttributes for this. You're basically rewriting logic, but not the end of the world: https://learn.microsoft.com/en-us/as.net/core/mvc/models/validation?view=as.netcore-6.0#custom-attributes

This will be able to perform what you want to do. If you don't like the sound of that, you'll probably want to look at writing middleware or filters in .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

Someone more learned than me may be able to tell you how to put this together in a nice way (as I don't know), but you'd essentially be replacing the inbuilt .NET Core validation logic with your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM