question

sanme98-3820 avatar image
0 Votes"
sanme98-3820 asked SimonBain-7705 published

How to set default query string parameter value for webapi?

May I know how to set a default query string value for webapi in .NET 6?

Example code:
[HttpGet]
public Greeting Greeting(string name)
{
return $"Hello {name}!";
}

The name parameter needs to have a default value, if I use string name = "world", it seems not working and throw
"errors":{"name":["The name field is required."]}

Thanks in advanced.

dotnet-aspnet-core-webapi
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @sanme98-3820,

if I use string name = "world", it seems not working and throw "errors":{"name":["The name field is required."]}

After changing the return data from Greeting to string, and set the default value, the code woks well on my side:

167053-1.gif

You can try to rebuild the application or create a new controller to check it. If it still shows the validation error. Please check your code is there any custom validation?

Best regards,
Dillion

0 Votes 0 ·
1.gif (203.8 KiB)

Hi Dillion,

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.

Thanks.

0 Votes 0 ·
AgaveJoe avatar image
1 Vote"
AgaveJoe answered sanme98-3820 commented

Try the following pattern.

 [HttpGet]
 public string Greeting(string name = "default value")
 {
     return $"Hello {name}!";
 }

You can also take a look at routing in ASP.NET Core

Routing in ASP.NET Core

Your sample code has an bug where you're returning a "Greeting" type but the actual return type is a string.


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Sorry, I have created a wrong example, in my actual scenario it should be Greeting, but if change to string, it get same result if just put blank on the name.

0 Votes 0 ·
ZhiLv-MSFT avatar image
0 Votes"
ZhiLv-MSFT answered SimonBain-7705 published

Hi @sanme98-3820,

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:

168170-image.png

In your scenario, to set the default value, you could try to use custom model binder. Refer to the following steps:

  1. 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;
             }
         }
    

  2. Register the custom binder provider.

      builder.Services.AddControllers(opt => {
             opt.ModelBinderProviders.Insert(0, new MyCustomBinderProvider());
         });
    

  3. 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:

168241-1.gif


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



image.png (167.2 KiB)
1.gif (2.2 MiB)
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

This is a perfect answer. Thanks it has saved me many hours - For OData and .net 6 If you are extending the call with your own query/values do not register the custom Binder just action it within your controller.

0 Votes 0 ·