简体   繁体   中英

Return pdf stored in blob storage using Azure HTTP Trigger Function (C#)

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.

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;
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM