Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 286

C# Serialize HttpRequest to Model Class in Azure Functions

$
0
0

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:


Viewing all articles
Browse latest Browse all 286

Trending Articles