How to set default query string parameter value for webapi?

San Me 1 Reputation point
2022-01-20T15:16:50.787+00:00

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.

Developer technologies | ASP.NET | ASP.NET Core
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 30,411 Reputation points
    2022-01-20T15:46:29.977+00:00

    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 person found this answer helpful.

  2. Anonymous
    2022-01-25T07:23:46.277+00:00

    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:

    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

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.