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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s