Routing In Azure Function

What is Routing ?

 
Routing is the process of directing an HTTP request to a controller which has the necessary business required to process the request and give an appropriate response. Using routing, we define the rules on the mapping between URLs to their respective controllers and actions. In the context of this article, It is the function route which can be used to send a http request to our Azure function.
 

Default function route in Azure functions

 
By default, the route for your azure function would be “localhost:7071/api/{functionName}”
  1. using System;  
  2. using System.IO;  
  3. using System.Threading.Tasks;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. using Microsoft.Azure.WebJobs;  
  6. using Microsoft.Azure.WebJobs.Extensions.Http;  
  7. using Microsoft.AspNetCore.Http;  
  8. using Microsoft.Extensions.Logging;  
  9. using Newtonsoft.Json;  
  10.   
  11. namespace CustomRouting  
  12. {  
  13.     public static class Function1  
  14.     {  
  15.         [FunctionName("Function1")]  
  16.         public static async Task<IActionResult> Run(  
  17.             [HttpTrigger(AuthorizationLevel.Function, "get""post", Route = null)] HttpRequest req,  
  18.             ILogger log)  
  19.         {  
  20.             log.LogInformation("C# HTTP trigger function processed a request.");  
  21.   
  22.             string name = req.Query["name"];  
  23.   
  24.             string requestBody = await new StreamReader(req.Body).ReadToEndAsync();  
  25.             dynamic data = JsonConvert.DeserializeObject(requestBody);  
  26.             name = name ?? data?.name;  
  27.   
  28.             string responseMessage = string.IsNullOrEmpty(name)  
  29.                 ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."  
  30.                 : $"Hello, {name}. This HTTP triggered function executed successfully.";  
  31.   
  32.             return new OkObjectResult(responseMessage);  
  33.         }  
  34.     }  
  35. }  
In the above snippet, the function route is http://localhost:7071/api/Function1
 

Custom Routing using the Route Parameter by modifying the route parameter in the HttpTriggerAttribute

 
We can update or override the route for our Http Triggered Azure function by modifying the route parameter in the function1.cs. By default the route parameter is assigned as null.
 
Suppose we want the route to send a request to our Azure function as localhost:7071/api/hello then we would need to simply assign the route parameter as hello.
  1. public static class Function1  
  2.     {  
  3.         [FunctionName("Function1")]  
  4.         public static async Task<IActionResult> Run(  
  5.             [HttpTrigger(AuthorizationLevel.Function, "get""post", Route = "Hello")] HttpRequest req,  
  6.             ILogger log)  
  7.         {  
  8.             log.LogInformation("C# HTTP trigger function processed a request.");  
  9.   
  10.             string name = req.Query["name"];  
  11.   
  12.             string requestBody = await new StreamReader(req.Body).ReadToEndAsync();  
  13.             dynamic data = JsonConvert.DeserializeObject(requestBody);  
  14.             name = name ?? data?.name;  
  15.   
  16.             string responseMessage = string.IsNullOrEmpty(name)  
  17.                 ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."  
  18.                 : $"Hello, {name}. This HTTP triggered function executed successfully.";  
  19.   
  20.             return new OkObjectResult(responseMessage);  
  21.         }  
  22.     }  
Now upon updating the route parameter, the new URL is http://localhost:7071/api/Hello
 

Passing value using function route in Azure function

 
We know that parameters or values can be passed with a url instead of using query string or request body in web applications and Web APIs. We often use this while we are sending a GET request to fetch data for a particular record.
 
Example - http://localhost:7071/api/Hello/1
 
To pass value in the function route in Azure function, we would have to modify the route parameter as “Hello/{valueName}”. Then add a parameter with the same name as the valueName in the Run method to use this value in your azure function. But adding {valueName} makes it a mandatory value to be passed.
  1. public static class Function1  
  2.     {  
  3.         [FunctionName("Function1")]  
  4.         public static async Task<IActionResult> Run(  
  5.             [HttpTrigger(AuthorizationLevel.Function, "get""post", Route = "Hello/{id}")] HttpRequest req,  
  6.             string id,  
  7.             ILogger log)  
  8.         {  
  9.             log.LogInformation("C# HTTP trigger function processed a request.");  
  10.   
  11.             string name = req.Query["name"];  
  12.   
  13.             string requestBody = await new StreamReader(req.Body).ReadToEndAsync();  
  14.             dynamic data = JsonConvert.DeserializeObject(requestBody);  
  15.             name = name ?? data?.name;  
  16.   
  17.             string responseMessage = string.IsNullOrEmpty(name)  
  18.                 ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."  
  19.                 : $"Hello, {name}. This HTTP triggered function executed successfully.";  
  20.   
  21.             return new OkObjectResult(responseMessage);  
  22.         }  
  23.     }  
Note
In case you don't pass a value in the function route, the request won't go to the Azure function. 
 
You can make it optional by adding a ? In the end of valueName like {valueName?}. Refer to the below snippet to make it optional in function route.
  1. public static class Function1  
  2.     {  
  3.         [FunctionName("Function1")]  
  4.         public static async Task<IActionResult> Run(  
  5.             [HttpTrigger(AuthorizationLevel.Function, "get""post", Route = "Hello/{id?}")] HttpRequest req,  
  6.             string id,  
  7.             ILogger log)  
  8.         {  
  9.             log.LogInformation("C# HTTP trigger function processed a request.");  
  10.   
  11.             string name = req.Query["name"];  
  12.   
  13.             string requestBody = await new StreamReader(req.Body).ReadToEndAsync();  
  14.             dynamic data = JsonConvert.DeserializeObject(requestBody);  
  15.             name = name ?? data?.name;  
  16.   
  17.             string responseMessage = string.IsNullOrEmpty(name)  
  18.                 ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."  
  19.                 : $"Hello, {name}. This HTTP triggered function executed successfully.";  
  20.   
  21.             return new OkObjectResult(responseMessage);  
  22.         }  
  23.     }  
Now upon updating the route parameter, the new URL can be http://localhost:7071/api/Hello/1 or http://localhost:7071/api/Hello or http://localhost:7071/api/Hello/ashirwad
 
Specifying the type of the valueName to be accepted in the function route.
 
By default, the type of valueName is string but you can also modify it to take value of a specific type by adding “:valueType” after the parameter name in the curly braces.
 
Example
 
To take an int type value in the function route you can specify the parameter as {valueName:int} and if you intend to make it optional then you can write it as {valueName:int?}.
 
You have to add a parameter in the run method with the same name and type as that of the valueName to use it in the business of your Azure function.
  1. public static class Function1  
  2.     {  
  3.         [FunctionName("Function1")]  
  4.         public static async Task<IActionResult> Run(  
  5.             [HttpTrigger(AuthorizationLevel.Function, "get""post", Route = "Hello/{id:int?}")] HttpRequest req,  
  6.             int id,  
  7.             ILogger log)  
  8.         {  
  9.             log.LogInformation("C# HTTP trigger function processed a request.");  
  10.   
  11.             string name = req.Query["name"];  
  12.   
  13.             string requestBody = await new StreamReader(req.Body).ReadToEndAsync();  
  14.             dynamic data = JsonConvert.DeserializeObject(requestBody);  
  15.             name = name ?? data?.name;  
  16.   
  17.             string responseMessage = string.IsNullOrEmpty(name)  
  18.                 ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."  
  19.                 : $"Hello, {name}. This HTTP triggered function executed successfully.";  
  20.   
  21.             return new OkObjectResult(responseMessage);  
  22.         }  
  23.     }  
Now upon updating the route parameter, the new URL can be http://localhost:7071/api/Hello/1 or http://localhost:7071/api/Hello 
 

Modifying the route prefix in Azure function

 
You must have noticed by now that almost all the function routes had /api/ in the route. In case, you wanted to change it, you can change it by modifying the content using the host.json.
 
Add the following snippet of line number 11 in the host.json to remove the route prefix in the function route.
  1. {  
  2.     "version""2.0",  
  3.   "logging": {  
  4.     "applicationInsights": {  
  5.       "samplingExcludedTypes""Request",  
  6.       "samplingSettings": {  
  7.         "isEnabled"true  
  8.       }  
  9.     }  
  10.   },  
  11.   "extensions": {"http": {"routePrefix"""}}  
  12. }  
Now upon updating the route parameter, the new URL can be http://localhost:7071/Hello/
 
In case you want to have a route prefix then you can add it inside the quotes of routePrefix in the above snippet. 
 

Conclusion

 
Routing is quite an essential part of developing an http based solution. Using the route, the request would map to the Azure function containing the business logic to perform the action for that particular request. It is quite flexible in Azure to configure a route as per your requirements. The above article discusses all the ways in which routing can be modified for an Azure function.