RequestEncoding settings on azure function app

63 views Asked by At

I have an Azure function app with a common trigger signature like this

public static async Task<IActionResult> RunAsync(
     [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
     ILogger log)

The request body "req.Body" doesn't have utf-8 encoding. For this particular application I need this specific encoding. How do I achieve this, I am using the azure function isolated process. In regular asp.net app I believe there is a globalization setting for this, if am not mistaken is like this.

<system.web>  
  <globalization   
    requestEncoding="utf-8"  
    responseEncoding="utf-8"/>  
</system.web>

How do I achive the same thing for the function app.

1

There are 1 answers

2
Vivek Vaibhav Shandilya On

This is how I was able to encode the data from request body.

I am using .NET 8 Isolated process

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using System.Text;

namespace FunctionApp5
{
    public class Function1
    {
        private readonly ILogger<Function1> _logger;

        public Function1(ILogger<Function1> logger)
        {
            _logger = logger;
        }

        [Function("Function1")]
        public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequest req)
        {
            _logger.LogInformation("C# HTTP trigger function processed a request.");
            using (StreamReader reader = new StreamReader(req.Body))
            {
                string requestBody = await reader.ReadToEndAsync();

                // Decode the bytes using UTF-8 encoding
                requestBody = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(requestBody));

                return new OkObjectResult($"Welcome to Azure Functions!\n decoded request body: {requestBody}");
            }
        }
    }
}

INPUT:

Hello Vivek, encoding data

OUTPUT:

Functions:

        Function1: [GET,POST] http://localhost:7158/api/Function1

For detailed output, run func with --verbose flag.
[2024-02-23T04:05:07.381Z] Host lock lease acquired by instance ID '000000000000000000000000116B5F66'.
[2024-02-23T04:05:23.996Z] Executing 'Functions.Function1' (Reason='This function was programmatically called via the host APIs.', Id=bc6d094e-48f5-4de7-b9e9-d26e884e19f6)
[2024-02-23T04:05:24.744Z] C# HTTP trigger function processed a request.
[2024-02-23T04:05:24.750Z] Executing OkObjectResult, writing value of type 'System.String'.
[2024-02-23T04:05:24.962Z] Executed 'Functions.Function1' (Succeeded, Id=bc6d094e-48f5-4de7-b9e9-d26e884e19f6, Duration=1037ms)

enter image description here

Welcome to Azure Functions!
 decoded request body: Hello Vivek, encoding data