Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify the HTTP method (verb) used to invoke an Azure Function

From the Azure Portal, we can easily create Function Apps. Once the Function App is created, we can add functions to the app.

In my case, from the custom templates, I'm selecting C#, API & Webhooks, and then selecting the Generic Webhook C# template.

From the Integrate menu, under the HTTP Header heading, there is a drop down box to with 2 selections: All Methods and Selected Methods. I then choose Selected Methods, and then have the option to select which HTTP methods the function can support. I would like my function to support GET, PATCH, DELETE, POST and PUT.

From within the C# run.csx code, how can I tell what method was used to invoke the method? I would like to be able to take different actions within the function code based on the HTTP method that was used to invoke the function.

Is this possible?

Thank you for your help.

like image 466
Yves Rochon Avatar asked Sep 28 '17 11:09

Yves Rochon


1 Answers

Answering my own question... you can examine the HttpRequestMessage's Method property, which is of type HttpMethod.

Here's the MSDN documentation:

  • HttpRequestMessage MSDN doc

  • HttpMethod MSDN Doc

HttpRequestMessage.Method Property

Gets or sets the HTTP method used by the HTTP request message.

  • Namespace: System.Net.Http
  • Assembly: System.Net.Http (in System.Net.Http.dll)

and a quick sample:

#r "Newtonsoft.Json"

using System;
using System.Net;
using Newtonsoft.Json;

public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info($"Webhook was triggered!");

    if (req.Method == HttpMethod.Post)
    {
        log.Info($"POST method was used to invoke the function ({req.Method})");
    }
    else if (req.Method == HttpMethod.Get)
    {
        log.Info($"GET method was used to invoke the function ({req.Method})");
    }
    else
    {
        log.Info($"method was ({req.Method})");    
    }
}
like image 180
Yves Rochon Avatar answered Oct 20 '22 06:10

Yves Rochon