Home > database >  What is wrong with this Azure function code?
What is wrong with this Azure function code?

Time:09-30

Just doing a simple test of Azure Functions.

Below is the DEFAULT code created when I add a function. In the code, you will see the original, commented out code which works just fine. Above that you will see the modified code that causes a 500 Internal Server Error. Now, at risk of looking like a complete idiot, I'm posting here, but super frustrated I'm wasting more than 5 seconds on this.

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

//  This code doesn't work (500 Internal Server Error)
    string responseMessage = "Hi!"
    return new OkObjectResult(responseMessage);

//  This default code does work
//    string responseMessage = string.IsNullOrEmpty(name)
//        ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
//                : $"Hello, {name}. This HTTP triggered function executed successfully.";
//
//            return new OkObjectResult(responseMessage);
}

CodePudding user response:

You have to find in the telemetry where the compilation errors are. It's not super-obvious in the edit-on-the-web experience. It's much easier when you develop and test in VS Code or Visual Studio.

This

    string responseMessage = "Hi!"
    return new OkObjectResult(responseMessage);

is missing a ; on the first line.

CodePudding user response:

When I return from a function, I do this:

var response = request.CreateResponse(HttpStatusCode.OK);
// add some headers to the response, like:
response.Headers.Add("Content-Type", "application/json");

// and then something like:
await response.WriteStringAsync(stuffToReturn); //(or could be WriteBytesAsync)

// and
return response;
  • Related