英文:
Can I customize error messages for values higher than allowed?
问题
我想在Swagger中设置自定义消息,当输入的值超过允许的最大值时。我在我的控制器中有以下方法:
public async Task<IActionResult> MyMethod(short someValue)
在.NET中,short的最大值为32767,如果我传递一个更高的值,我会收到错误消息:“值 '999999' 无效”。是否有一种方法来自定义该消息?
英文:
I want to set a custom messagem when a higher value than allowed is informed, at swagger.
I have the following method in my controller:
public async Task<IActionResult> MyMethod(short someValue)
The max value for short in .Net is 32767, if I pass a higher value, I got the error message: "The value '999999' is not valid.", is there a way to customize that message?
答案1
得分: 1
这是一个模型绑定错误,而不是模型验证错误,你可以尝试在这里设置:
builder.Services.AddControllers(op => op.ModelBindingMessageProvider.SetNonPropertyAttemptedValueIsInvalidAccessor(input => input + " invalid"));
结果:
要获得更详细的错误消息,你需要自定义模型绑定器,例如:
public class MyBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var modelName = bindingContext.ModelName;
// 尝试按名称获取参数的值
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
var value = valueProviderResult.FirstValue;
if (!short.TryParse(value, out var id))
{
// 添加逻辑以比较值等等
bindingContext.ModelState.TryAddModelError(
modelName, value + " 不是有效的 short 值。");
return Task.CompletedTask;
}
return Task.CompletedTask;
}
}
应用模型绑定器:
[ModelBinder(BinderType = typeof(MyBinder))] short someValue
英文:
It's a modelbinding error not model validation error,you may try set here:
builder.Services.AddControllers(op => op.ModelBindingMessageProvider.SetNonPropertyAttemptedValueIsInvalidAccessor(input => input+" invalid")) ;
Result:
For more detailed error message, you need to custom model binder,for example:
public class MyBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var modelName = bindingContext.ModelName;
// Try to fetch the value of the argument by name
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
var value = valueProviderResult.FirstValue;
if (!short.TryParse(value, out var id))
{
// add the logical compare the value and so on
bindingContext.ModelState.TryAddModelError(
modelName, value+" is not valid for short.");
return Task.CompletedTask;
}
return Task.CompletedTask;
}
}
Apply the modelbinder :
[ModelBinder(BinderType = typeof(MyBinder))] short someValue
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论