Optional Parameters in Web API

Let us see how to make one or more parameters as optional in Web API.

[HttpGet]
[Route("Vehicles/GetDetails/{CompanyID}/{VehicleType}/{ModelNo}")]
public HttpResponseMessage GetDetails(String CompanyID, string VehicleType, string ModelNo)
{
    ...
}

Usually this method can be called like –

http://127.0.0.2:9966/Vehicles/GetDetails/101/SUV/DK999

If we want to make VehicleType as optional and pass it as null value like below, it will throw an error.

http://127.0.0.2:9966/Vehicles/GetDetails/101//DK999

 

This can be accomplished by moving all the optional parameters to last, assigning them a default value and passing them as separate values in the URL.

The method should be modified as –

[HttpGet]
[Route("Vehicles/GetDetails/{CompanyID}/{ModelNo}")]
public HttpResponseMessage GetDetails(String CompanyID, string ModelNo, string VehicleType = "ALL")
{
    ...
}

Then we can call the method as –

http://127.0.0.2:9966/Vehicles/GetDetails/101/DK999?VehicleType=SUV

We can also add it to body as well.

Leave a Reply

Your email address will not be published. Required fields are marked *