Hi @San Me ,
It is ok if the name is with a value, how about it you put in blank for the name? For my side, it get the error if name is blank although it has set to have a default value in parameter there.
I understand you. If the name is blank, it will show the 400 model invalid error:
In your scenario, to set the default value, you could try to use custom model binder. Refer to the following steps:
- Create a custom model binder.
//required reference: using Microsoft.AspNetCore.Mvc.ModelBinding;
// using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
public class CustomModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var model = string.Empty;
if (bindingContext.ValueProvider.GetValue("name").FirstOrDefault() != null)
{
//if the parameter is not null. get the value.
pragma warning disable CS8604 // Possible null reference argument.
model = bindingContext.ValueProvider.GetValue("name").FirstOrDefault();
pragma warning restore CS8604 // Possible null reference argument.
}
else
{
//set the default value.
model = "Default Value";
}
bindingContext.Result = ModelBindingResult.Success(model);
return Task.CompletedTask;
}
}
public class MyCustomBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
// specify the parameter your binder operates on
if (context.Metadata.ParameterName == "param2")
{
return new BinderTypeModelBinder(typeof(CustomModelBinder));
}
return null;
}
}
- Register the custom binder provider.
builder.Services.AddControllers(opt => {
opt.ModelBinderProviders.Insert(0, new MyCustomBinderProvider());
});
- Applying ModelBinding Attribute on Action method
// GET: api/<ToDoController>
[HttpGet]
public string Get([ModelBinder(BinderType = typeof(CustomModelBinder))]string name)
{
//return new string[] { "value1", "value2" };
return $"Hello {name}!";
}
Then, the result is like this:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion