Types of Route Parameters Required Parameters: Syntax: Enclosed in curly braces {}. Behavior: Must be provided in the URL for the route to match. If not present, the request won’t match this endpoint. Example: /products/{id} (The id parameter is required). Optional Parameters: Syntax: Enclosed in curly braces {} and followed by a question mark ?. Behavior: Can be omitted from the URL. If not present, the parameter’s value will be null. Example: /products/details/{id?} (The id parameter is optional). Parameters with Default Values: Syntax: Enclosed in curly braces {}, followed by an equals sign =, and then the default value. Behavior: If not provided in the URL, the parameter will take the specified default value. Example: /employee/profile/{EmployeeName=harsha} (The EmployeeName parameter defaults to “harsha”). Code: // … (UseRouting and other middleware) …
// Optional Parameter endpoints.Map(“products/details/{id?}”, async context => { if (context.Request.RouteValues.ContainsKey(“id”)) { int id = Convert.ToInt32(context.Request.RouteValues[“id”]); await context.Response.WriteAsync($”Products details – {id}”); } else { await context.Response.WriteAsync($”Products details – id is not supplied”); } }); });
// … (Fallback middleware) …
Required Parameters Example: The route files/{filename}.{extension} expects both filename and extension to be present in the URL (e.g., /files/sample.txt). The endpoint handler extracts these values from context.Request.RouteValues and uses them in the response. Default Parameter Example: The route employee/profile/{EmployeeName=harsha} has a default value for EmployeeName. If you visit /employee/profile, the response will be “In Employee profile – harsha”. If you visit /employee/profile/john, the response will be “In Employee profile – john”. Optional Parameter Example: The route products/details/{id?} allows the id parameter to be omitted. If you visit /products/details/123, it will show the product details for ID 123. If you visit /products/details, it will indicate that the ID was not provided.