aplon
aplon

Reputation: 477

Pass FormFile parameter before it is disposed to fire-and-forget method

I have an API Controller with a method that receives a File as a parameter. I need to pass the File as a parameter to an async fire-and-forget method to process it. To do so, I "inject" the file to a lambda function, resposible for executing de F&F method. However, when executing the F&F method, the file has always beed disposed.

How can I pass a FormFile to a F&F method, without the file being disposed?

This is what I am doing:

[HttpPost]
[Route("example-route")]
public async Task<bool> CannonExcelContactsListUpload(Microsoft.AspNetCore.Http.IFormFile formFile)
{
    this.CannonService.FireAsync<ExampleLogicClass, Microsoft.AspNetCore.Http.IFormFile>(
    async (logic, file) =>
    {
        await logic.ExampleFireAndForgetMethodAsync(file);
    },
    formFile
);

    return true;
}

Upvotes: 1

Views: 51

Answers (1)

Charlieface
Charlieface

Reputation: 71467

You need to buffer the file into a MemoryStream otherwise it's disposed as soon as the request function is finished.

[HttpPost]
[Route("example-route")]
public async Task<bool> CannonExcelContactsListUpload(IFormFile formFile)
{
    var ms = new MemoryStream();
    await formFile.CopyToAsync(ms);
    this.CannonService.FireAsync<ExampleLogicClass, Stream>(async (logic, file) =>
        {
            await logic.ExampleFireAndForgetMethodAsync(file);
        },
        ms
    );

    return true;
}

Upvotes: 1

Related Questions