.Net 6.0 Web Api, Pass empty string as parameter value

Viewed 1731

I'm start work with .Net 6 web api. I have write a controller very simple:

[Route("[controller]")]
[ApiController]
public class TestController : ControllerBase
{
  [HttpGet,Route("sample")]
  public IActionResult ReturnSample(string ParameterOne, string ParameterTwo)
  {
    [... do something ...]
  }
}

The problem is who all parameter are madatory.

URL: https:///test/sample?ParameterOne=Value&ParameterTwo=Value

Work fine, all OK

URL: https:///test/sample?ParameterOne=Value&ParameterTwo=

ERROR: {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-dc73d9983b53750d2073c48bec522c70-98fe251af1accccf-00","errors":{"ParameterTwo":["The ParameterTwo field is required."]}}

How can I allow empty value as valid value for parameter.

Thanks Lorenzo

2 Answers

You can set the default value for the second parameter:

[HttpGet,Route("sample")]
public IActionResult ReturnSample(string ParameterOne, string? ParameterTwo = null)
{
   // ...
}

If you don't want to send value at all, you can try using ?:

[HttpGet("{ParameterOne?}/{ParameterTwo?}"),Route("sample")]
public IActionResult ReturnSample(string ParameterOne = null, string ParameterTwo = null)
{
 [... do something ...]
}

Note: if you have two parameters and just one of them could have a value, then the second parameter that has value as null should be always in your uri in the end:

[HttpGet("{ParameterOne?}/{ParameterTwo}")] => wrong
[HttpGet("{ParameterTwo}/{ParameterOne?}")] => correct

Related