19

How to make a route parameter optional in Azure Function

public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "ResolveKey/{key}/{resolver}")]HttpRequestMessage req, TraceWriter log, string key,string resolver= "default")

In the above code I tried to make resolver parameter optional by setting a default value string resolver= "default" . The code compiles and runs fine, but the URL always wants resolver parameter to be present, otherwise I get 404.

I want to make the resolver parameter optional in the above code. Is there any way?

Janusz Nowak
  • 2,595
  • 1
  • 17
  • 36
Ramkumar Singh
  • 2,240
  • 4
  • 15
  • 18

3 Answers3

42

You can express that a parameter is optional in the route template itself.

For the route above, you can just change your template to the following:

ResolveKey/{key}/{resolver?}

You can find more information about optional routes and default values here

Fabio Cavalcante
  • 12,328
  • 3
  • 35
  • 43
  • 1
    For those who are looking to match a full path in the resolver, Azure function will url encode the `{resolver?}` match by default. You will need to include an app setting to work around this, `AZURE_FUNCTION_PROXY_BACKEND_URL_DECODE_SLASHES : true`. (https://github.com/Azure/azure-functions-host/issues/2249#issuecomment-391167871) – James Aug 30 '20 at 19:42
3

Azure Functions now support regular expressions. You can change your routing template to

ResolveKey/{key}/{*resolver}
Eelco Koster
  • 138
  • 1
  • 3
1

The previous answers helped me out but I would have spent even less time if I had seen an example. Here I provide you one:

Optional Azure Function Parameter example

Luis Gouveia
  • 8,334
  • 9
  • 46
  • 68