Azure / azure-functions-dotnet-worker-preview

MIT License
65 stars 19 forks source link

How to Deserialize json in HttpRequestData Body #51

Closed alexanderbikk closed 3 years ago

alexanderbikk commented 3 years ago

I have the following http trigger.

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;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net;

namespace WorldcatPOC.Functions
{
   public class Test
   {
      public string Name { get; set; }
   }

  public static class SyncCase
  {
    [FunctionName("SyncCase")]
    public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req,
        FunctionExecutionContext executionContext)
    {
        var logger = executionContext.Logger;
        logger.LogInformation("message logged");
        logger.LogInformation(req.Body);

        var testObject = JsonConvert.DeserializeObject<Test>(req.Body);
        if (testObject.Name == null)
        {
            logger.LogInformation("Name is null");
        }

        var response = new HttpResponseData(HttpStatusCode.OK);
        var headers = new Dictionary<string, string>();
        headers.Add("Date", "Mon, 18 Jul 2016 16:06:00 GMT");
        headers.Add("Content", "Content - Type: text / html; charset = utf - 8");

        response.Headers = headers;
        response.Body = "Welcome to .NET 5!!";

        return response;
       }
   }
}

I call it via Postman and put the json data {"Name":"test name"}. But the req.Body property looks like { "json": "{\"Name\":\"test name\"}" } I'm a little bit confusing why the Body looks like this? It won't be deserialized properly in my Test object without parsing.

jeffhollan commented 3 years ago

This should be fixed if you move to preview4 for the worker Nuget

jeffhollan commented 3 years ago

Ah I don’t see preview4 in nuget? @fabiocav do you know when that’s being published or if I’m missing something?

alexanderbikk commented 3 years ago

Thank @jeffhollan. I also thought about using preview4 after investigating your repo but it's not available.

Anyway, I know that it's a bug, so I'm waiting for preview4. Thanks again for such a quick answer :)

fabiocav commented 3 years ago

Preview 4 will be up today. Will provide an update here once it's up.

fabiocav commented 3 years ago

The package has been published. I'm also updating the sample app here with some additional HTTP examples.

alexanderbikk commented 3 years ago

Hi, @fabiocav cool thanks a lot! :) I confirm that my example works right now. Just replaced the Body property with ReadAsString() method like in your example. Any thoughts on when the stable version will be available? :)

Btw, how to deploy the new function with .net5 to Azure using AzureDevops? Does the Azure Function task support it?