Aidan
Aidan

Reputation: 4901

How to return a stream from an Azure Function?

I am trying to write an Azure Function v2 using dotnet core as part of a durable function. I want to create an activity function that reads a file from blob storage, decrypts it and returns the decrypted byte stream. I can create the decrypted stream ok and am trying to return the stream like this:

[FunctionName("Decrypt")]
public static async Task<IActionResult> Run(
    [ActivityTrigger] string blobName,
    ILogger log,
    ExecutionContext context)
{
    // get stream from blob storage

    var bytes = await GetDecryptedByteArrayAsync(blobStream);
    return new FileContentResult(bytes, "application/octet-stream");
}

This appears to work, but when I try to read the response like this:

        var provisioningArchive = await
            ctx.CallActivityAsync<FileContentResult>("Decrypt", encryptedBlobName);

I get the following exception:

Newtonsoft.Json.JsonSerializationException: Unable to find a constructor to use for type Microsoft.AspNetCore.Mvc.FileContentResult. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor

How can I get this to deserialise into an object that represents the stream?

Upvotes: 4

Views: 9355

Answers (2)

Aidan
Aidan

Reputation: 4901

I don't think it's possible to return a Stream to an Orchestration context, as the Bindings documentation says that the return values must be serializable to JSON:

Return values - Return values are serialized to JSON and persisted to the orchestration history table in Azure Table storage. These return values can be queried by the orchestration client binding, described later.

I got round this by creating a Dto to wrap the raw byte array:

public class StreamDto
{
    public string Name { get; set; }
    public byte[] Contents { get; set; }
}

and return that instead. Since it is serializable to Json, I can pass it back and forth and recreate the stream in the activity function.

Upvotes: 8

Related Questions