Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter to Azure Function (HttpTrigger) in URL as querystring

Created a new Azure Function in Visual Studio 2017 (HTTPTrigger based) and having difficulty passing parameters with custom route. Below is the code excerpt:

[FunctionName("RunTest")]
public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "orchestrators/contoso_function01/{id:int}/{username:alpha}")] HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    // parse query parameter
    string name = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "id", true) == 0)
        .Value;

    string instanceId = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "username", true) == 0)
        .Value;

    if (name == null)
    {
        // Get request body
        dynamic data = await req.Content.ReadAsAsync<object>();
        name = data?.name;
    }

    return name == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
}

I tried to access the Function with the below URLs, but couldn't retrieve the ID or UserName values from the query string using the GetQueryNameValuePairs() API, as it has only 0 items in the collection:

http://localhost:7071/api/orchestrators/contoso_function01/123/abc
http://localhost:7071/api/orchestrators/contoso_function01/?id=123&username=abc
like image 734
Karthik Avatar asked Jun 07 '26 15:06

Karthik


2 Answers

If you want to use parameters in the URL itself instead of reading them from the HttpRequestMessage req object, the following can be done,

Example URL:

http://localhost:7201/api/orchestrators/contoso_function01/{id}/{username}

Supporting code:

[FunctionName("RunTest")]
public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", 
        Route = "orchestrators/contoso_function01/{id}/{username}")]
    HttpRequestMessage req, int id, string username, TraceWriter log)
{
    log.Info($"Id = {id}, Username = {username}");
    // more code goes here...
}

Here we made two changes:

  1. Adding id and username as part of URL.

    Route = "orchestrators/contoso_function01/{id}/{username}"

  2. Declaring two additional variables for id and username. The name of the variables has to match the parameter name in the URL (case insensitive).

    HttpRequestMessage req, int id, string username, TraceWriter log

Side Note: Do not remove the HttpRequestMessage req from the function paramter even if it is not used in your code. Removing the same will stop binding of the parameters (not sure if it is intended or a bug).

This solution was tested on Azure Functions Version 3.

Further Reading: Serverless C# with Azure Functions: HTTP-Triggered Functions.

like image 70
ihimv Avatar answered Jun 10 '26 06:06

ihimv


Not sure if this is the right way to handle such a need to pass parameters for HTTP Requests with Azure Functions, but if I include parameters for each of the query string with matching parameter names (which apparently is mandatory to get the bindings work), it automatically gets assigned with the value passed in the URL to the respective parameter.

[FunctionName("HttpRunSingle")]
public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "orchestrators/contoso_function01/{id:int}/{username:alpha}")]
    HttpRequestMessage req,
    int id,
    string username,
    TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");
            
    return (id == 0 || string.IsNullOrEmpty(username))
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, "Hello " + id + " " + username);
}
like image 20
Karthik Avatar answered Jun 10 '26 06:06

Karthik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!