Home > other >  How to make other methods call after return OK response to client in ASP.Net Core
How to make other methods call after return OK response to client in ASP.Net Core

Time:05-08

I am using the asp.net core WebAPI Project in which a client is uploading some files to a server. The whole uploading is done using chunks.

The problem is when I am uploading a huge file then I am getting a response after a very long time. So what I want to do is when all the chunks are uploaded on a server then send an OK response to the client and do the chunks merging related stuff after the OK response.

Here is my code:

public async Task<ActionResult> Upload(int currentChunkNo, int totalChunks, string fileName)
{
            try
            {
                string newpath = Path.Combine(fileDirectory   "/Chunks", fileName   currentChunkNo);
                using (FileStream fs = System.IO.File.Create(newpath))
                {
                    byte[] bytes = new byte[chunkSize];
                    int bytesRead = 0;
                    while ((bytesRead = await Request.Body.ReadAsync(bytes, 0, bytes.Length)) > 0)
                    {
                        fs.Write(bytes, 0, bytesRead);
                    }
                }
                return Ok(repo.MergeFile(fileName));
            }
            catch (Exception ex)
            {
                return BadRequest(ex);
            }
}

CodePudding user response:

You can use middleware for process after action run.

First create your middleware

public class UploadMiddleware
{
    private readonly RequestDelegate _next;

    public UploadMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    // you can inject services here

    public async Task InvokeAsync(HttpContext httpContext)
    {
        // before request

        await _next(httpContext);

        // YourController/Upload is your path on route
        // after any action ended
        if (httpContext.Response != null &&
            httpContext.Response.StatusCode == StatusCodes.Status200OK &&
            httpContext.Request.Path == "YourController/Upload") 
        { 
            // another jobs
        }

    }
}

Use Middleware

app.UseMiddleware<UploadMiddleware>();
  • Related