I have a controller with the following signature:
[Route("products/filter/{apc=apc}/{xpc=xpc}/{sku=sku}")] public IHttpActionResult Get(string apc, string xpc, int? sku) { ... }
I call this method with following URIs:
The first URI works without issue. The second one has a strange side effect. Even though the default values for apc and xpc should be null when not provided, the parameters are actually their names. I can overcome this by adding the additional logic:
apc = (apc == "apc") ? null : apc; xpc = (xpc == "xpc") ? null : xpc;
This seems like a hack, and would be problematic if value passed was ever equal to the parameter name.
Is there a way to define the Route without this side effect?
Optional Parameters in Web API Attribute Routing and Default Values: You can make a URI parameter as optional by adding a question mark (“?”) to the route parameter. If you make a route parameter as optional then you must specify a default value by using parameter = value for the method parameter.
You can then use @DefaultValue if you need it: @GET @Path("/job/{param1}/{param2}") public Response method(@PathParam("param1") String param1, @PathParam("param2") String param2, @QueryParam("optional1") String optional1, @QueryParam("optional2") @DefaultValue("default") String optional2) { ... }
Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters.
By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.
I figured it out. I was using a bad example I found in the past of how to map query string to the method parameters.
In case anyone else needs it, in order to have optional parameters in a query string such as:
you would use:
[Route("products/filter/{apc?}/{xpc?}/{sku?}")] public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null) { ... }
It seems odd to have to define default values for the method parameters when these types already have a default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With