English 中文(简体)
Can 我对高于允许的价值的错误信息进行定制?
原标题:Can I customize error messages for values higher than allowed?

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)

短期最高值。 净额为32767,如果我具有更高的价值,那么我就拿到了错误的信息:“价值9999999不有效”,是否有办法定制这一信息?

问题回答

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:

enter image description here

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))
            {
                
                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

Result: enter image description here





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签