Overriding ModelBindingMessageProvider error messages

可紊 提交于 2020-04-18 03:49:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!