Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swashbuckle.AspNetCore required query string parameter

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

like image 512
Oleg Sh Avatar asked May 17 '19 12:05

Oleg Sh


People also ask

Can we make query param mandatory?

Yes, mandatory parameters can be used in query parameters. In that case you need to put a validation after the API is hit to check whether the value of the parameter is not null and is of specified format.

Are query parameters always optional?

Query parameters are the most common type of parameters. They appear at the end of the request URL after a question mark ( ? ), with different name=value pairs separated by ampersands ( & ). Query parameters can be required and optional.

What is FromQuery in C#?

[FromQuery] - Gets values from the query string. [FromRoute] - Gets values from route data. [FromForm] - Gets values from posted form fields. [FromBody] - Gets values from the request body.


2 Answers

You can add the BindRequired attribute to your parameter.

public async Task<IActionResult> SetToken([FromQuery, BindRequired]string token)
like image 99
ESG Avatar answered Jan 29 '23 20:01

ESG


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.

like image 23
Oswaldo Junior Avatar answered Jan 29 '23 19:01

Oswaldo Junior