我可以自定义超出允许范围的错误消息吗?

huangapple go评论152阅读模式
英文:

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&lt;IActionResult&gt; 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 =&gt; op.ModelBindingMessageProvider.SetNonPropertyAttemptedValueIsInvalidAccessor(input =&gt; input+&quot; invalid&quot;)) ;

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+&quot; is not valid for short.&quot;);

                return Task.CompletedTask;
            }


            return Task.CompletedTask;
        }
    }

Apply the modelbinder :

[ModelBinder(BinderType = typeof(MyBinder))] short someValue

Result:
我可以自定义超出允许范围的错误消息吗?

huangapple
  • 本文由 发表于 2023年8月11日 03:19:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76878750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定