I am trying to set up an .NET 5 Azure Http function that takes a request with a json body and outputs it to the logs.
using System.Threading.Tasks;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Pipeline;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
namespace MyProject.Test
{
public sealed class Function
{
[FunctionName("Test")]
public async Task RunAsync(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
HttpRequestData requestData,
FunctionExecutionContext executionContext)
{
executionContext.Logger.LogInformation(requestData.Body);
}
}
}
I post a json body to using Postman
{
"myProperty": "abc123"
}
Which outputs
{ "json": "{\"myProperty\":\"abc123\"}" }
I'm not sure why the function is wrapping the body in { "json": "" }
.
Have I set up the function incorrectly? Or is it set up correctly and there is another way I can access the raw body?
Turns out I followed an out of date guide for setting up .NET 5 Http Functions. THe official microsoft guide works. https://learn.microsoft.com/en-gb/azure/azure-functions/dotnet-isolated-process-guide
This requires some of these packages to be added to .csproj
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.0.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.12" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.0.1" OutputItemType="Analyzer" />
<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="5.0.0" />
<PackageReference Include="System.Net.NameResolution" Version="4.3.0" />
<PackageReference Include="System.Text.Json" Version="5.0.1" />
</ItemGroup>
And the function now looks like this
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
namespace MyProject.Test
{
public sealed class Function
{
[Function("Test")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
HttpRequestData requestData,
FunctionContext context)
{
var myclass = await System.Text.Json.JsonSerializer.DeserializeAsync<MyClass>(requestData.Body);
context.GetLogger("Test").LogInformation(myclass.MyProperty);
var response = requestData.CreateResponse(System.Net.HttpStatusCode.OK);
return response;
}
public class MyClass
{
[JsonPropertyName("myProperty")]
public string MyProperty { get; set; }
}
}
}
The json body now gets serialized correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With