问题
I have a .net core 2.2 webapi. There is a POST
action that accepts a model. The model has a Guid
as one of the properties. When I post this model but supply a string and not a Guid, I get a ModelState.IsValid = false
, which is correct. The default model binding error message is "Error converting value \"string\" to type 'System.Guid'. Path 'memberId', line 3, position 22."
This is not a friendly message that I want to return, also, this message needs to get localized to user's language. All the resources that I have read said I need to set the accessor for ModelBindingMessageProvider
in the AddMvC()
options. i.e.
services.AddMvc(options => options.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((x, y) => "blah blac");
I have set ALL of the accessors on there and it still doesn't change the default message. Anyone knows how to set those default values?
回答1:
The issue is that the InputFormatter
is throwing exception and the exception message is used for the modelstate entry. You can disable this in services.AddMvc().AddJsonOptions(options => options.AllowInputFormatterExceptionMessages = false;)
. This will add an empty string for the error message, which you can detect and then just display a generic message to user. I have not found a better way of doing this but this method will suffice for now.
来源:https://stackoverflow.com/questions/54859476/overriding-modelbindingmessageprovider-error-messages