Home > other >  Azure Function Return String in Http Response
Azure Function Return String in Http Response

Time:09-16

This seems simple but I guess the syntax / libraries have changed so many times, finding a sample is like trying to trace the entire path of a single thread of spaghetti in a massive bowl of bolognaise.

I have the following C# dotnet 5 Azure Function:

public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequestData req,
            ILogger log)

string result = "for the love of god, I just want to return this string"

I would like to return the "result" string with a 200 response code.

I tried the following

return result != null ? New OkObjectResult(result) : new StatusCodeResult(500);

But rather than returning a string, it returns:

{
  "Value": "content of result variable here",
  "Formatters": [],
  "ContentTypes": [],
  "DeclaredType": null,
  "StatusCode": 200
}

Any ideas?

CodePudding user response:

With the new 'isolated' model, your application now runs in a separate process to the function host. Microsoft provide a list of benefits when running out-of-process, and the key benefit is being able to have different versions of a dll to the function host without having conflicts at runtime (something that I have had to deal with frequently in the past).

Since your application is running as a separate process to the host, you can't just return an object reference as output from your function. That object has to be serialized, in order to be sent back to the host process. This means input and output bindings can't be functional objects, only serializable data, so most of the input and output bindings (including IActionResult) have been simplified. By default, if you try to return an object, it will be serialized as json, which is what you are seeing when you return new OkObjectResult(result). If you want to serialize it explicitly, you need to return HttpResponseData, and it's much more involved than before:

[Function("HttpFunction")]
public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req)
{
    var json = JsonConvert.SerializeObject("for the love of god, I just want to return this string");
    var response = req.CreateResponse(HttpStatusCode.OK);
    response.Headers.Add("Content-Type", "text/json; charset=utf-8");
    response.WriteString(json);
    return response;
}
  • Related