The signature of Http triggered Azure Functions include a HttpRequest:
[Function("MyFunction")]
public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req)
{
// first order of things is to get the request body and serialize it into a class
}
The HttpRequest is not serialized by default, as it is when working with controllers in .net. So we need to do it ourselves.
This can be achieved with a simple extension method:
using Microsoft.AspNetCore.Http;
namespace AzureFunctionApp.Foundation.Extensions
{
public static class HttpRequestExtension
{
public static async Task<T?> DeserializeAsync<T>(this HttpRequest req)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var options = new System.Text.Json.JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
return System.Text.Json.JsonSerializer.Deserialize<T>(requestBody, options);
}
}
}
Now, in the Azure Function, the first line of code will be to read the body into a model class:
[Function("MyFunction")]
public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req)
{
// first order of things is to get the request body and serialize it into a class
var request = await req.DeserializeAsync<MyModelClass>();
// now you can work with the data from the request body:
var field = request.SomeField;
}
That’s it. You are now an Azure Function expert. Happy coding.
MORE TO READ:
- HttpRequest Class from Microsoft
- Azure Functions: No job functions found. Try making your job classes and methods public. by briancaos