Default values

Default values are defined by placing an equals sign next to the route parameter. Note that placing default values on the method parameters (not in the root template) will not work, as the routing pipeline is unable to find a match by looking at optional parameters.

For example, the GiveNTake application allows the user to search for products by specifying a category and a sub-category; however, the sub-category is optional, and if it is omitted, the default subcategory will be all. The following code snippet shows you how to define these rules:

[HttpGet("searchcategory/{category}/{subcategory=all}/")]
public string[] SearchByProducts(string category,string subcategory)
{
return new[]
{
$"Category: {category}, Subcategory: {subcategory}"
};
}

Run the application and navigate to http://localhost:[port]/api/products/searchcategory/furniture/kitchen, and then to http://localhost:[port]/api/products/searchcategory/furniture.

For the first URL, you should see results similar to the following:

And the second URL should produce an output like this:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.181.186