10

I have an ASP.NET Core v2.1 project with Swashbuckle.AspNetCore package. My code is:

    /// <summary>
    /// Set new android token for the current driver
    /// </summary>
    /// <remarks>
    /// Sample request:
    ///
    ///     PUT /SetToken?token=new_token
    ///
    /// </remarks>
    /// <param name="token">can't be null or empty</param>
    /// <returns></returns>
    /// <response code="204">If executed successfully</response>
    /// <response code="400">if token is null or empty</response>  
    /// <response code="404">if user is not a driver; if driver is not found (removed etc); if user does not have a profile</response>  
    [ProducesResponseType(204)]
    [ProducesResponseType(400)]
    [ProducesResponseType(404)]
    [HttpPut]
    [Route("SetToken")]
    [UserIsNotDriverException]
    [NullReferenceException]
    [DriverWithoutProfileException]
    public async Task<IActionResult> SetToken([FromQuery]string token)
    {

I want to mark query parameter as required. How can I do it? Pay attention, I pass parameter in query string, not inside body etc

Oleg Sh
  • 8,496
  • 17
  • 89
  • 159
  • The query string is inherently optional. That's just HTTP spec. If you need to require something, it should be part of the route (i.e. the actual URL path). That said, methods like POST and PUT have a request body, and the proper place for data is in the body. You should pretty much never be using query strings with something like a PUT. – Chris Pratt May 17 '19 at 12:44

2 Answers2

24

You can add the BindRequired attribute to your parameter.

public async Task<IActionResult> SetToken([FromQuery, BindRequired]string token)
ESG
  • 8,988
  • 3
  • 35
  • 52
  • 2
    This requires at least .Net Core 2.1 in order for "ModelState.IsValid" to function correctly, see: https://andrewlock.net/coming-in-asp-net-core-2-1-top-level-mvc-parameter-validation/ – goamn Oct 14 '19 at 05:38
2

You can do it like this.

public async Task<IActionResult> SetToken([FromQuery, SwaggerParameter("Token Description", Required = True)]string token)

Using this library Swashbuckle.AspNetCore.Annotations will help.