覆盖ModelBindingMessageProvider错误消息 [英] Overriding ModelBindingMessageProvider error messages
问题描述
我有一个.net core 2.2 webapi。有一个 POST
动作可以接受一个模型。该模型具有 Guid
作为属性之一。当我发布此模型但提供字符串而不是Guid时,我得到了 ModelState.IsValid = false
,这是正确的。默认的模型绑定错误消息是将值\ string\转换为类型'System.Guid'时出错。路径'memberId',第3行,位置22。
这不是我要返回的友好消息,而且该消息需要本地化为用户的语言。我已阅读的所有资源都说我需要在 AddMvC()
选项中为 ModelBindingMessageProvider
设置访问器。即
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?
推荐答案
问题是 InputFormatter
抛出异常,并且异常消息用于modelstate条目。您可以在 services.AddMvc()。AddJsonOptions(options => options.AllowInputFormatterExceptionMessages = false;)
中禁用此消息。错误消息的空字符串,您可以检测到该字符串,然后仅向用户显示一条通用消息。我没有找到更好的方法,但是此方法现在就足够了。
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.
这篇关于覆盖ModelBindingMessageProvider错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!