Home > Software engineering >  Return pdf stored in blob storage using Azure HTTP Trigger Function (C#)
Return pdf stored in blob storage using Azure HTTP Trigger Function (C#)

Time:08-27

I'm using C# and .NET6 I have a HTTP trigger function that using Blob input binding to get a PDF file from the blob storage.
I'm having trouble with the return type of that function.
I already know I have the blob content because its length > 0.

This is my code:

public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = "foo/{bar}")] HttpRequest req,
    [Blob("foo/{bar}.pdf", FileAccess.Read)] Stream blobContent,
    ILogger log, string bar)
{
    if (blobContent == null)
    {
        // TODO return error page:
        return new OkResult();
    }
    else
    {
        // Return pdf from blob storage:
        blobContent.Seek(0, SeekOrigin.Begin);
        FileStreamResult fsr;
        try
        {
            fsr = new FileStreamResult(blobContent, MediaTypeNames.Application.Pdf);
        }
        catch (Exception e)
        {
            log.LogError(e, "Error returning blobcontent");
            throw;
        }
            
        return fsr;
    }
}

While debugging I can see blobContent has content.
But when I run it to the end I get this error in the terminal:

An unhandled host error has occurred.
System.Private.CoreLib: Value cannot be null. (Parameter 'buffer').

So I'm not handling the blobContent correctly.
How do I return the stream properly?

It seems so trivial and I can't even find an example for such simple.

CodePudding user response:

Switch to byte[] as your input and the just use FileContentResult

    [FunctionName("Blob2Http")]
    public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", Route = "blob/{filename}")] HttpRequest req,
    [Blob("test/{filename}.pdf", FileAccess.Read)] byte[] blobContent,
    ILogger log, string filename)
    {
        if (blobContent == null)
        {
            // TODO return error page:
            return new OkResult();
        }
        else
        {
            try
            {
                return new FileContentResult(blobContent, MediaTypeNames.Application.Pdf)
                {
                    FileDownloadName = $"{filename}.pdf"
                };
            }
            catch (Exception e)
            {
                log.LogError(e, "Error returning blobcontent");
                throw;
            }
        }
    }
  • Related