如何在 return OK 响应 ASP.Net Core 中的客户端后调用其他方法

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

我正在使用 asp.net 核心 WebAPI 项目,其中客户端正在将一些文件上传到服务器。整个上传都是分块完成的。

问题是当我上传一个巨大的文件时,我在很长时间后才收到回复。所以我想做的是,当所有块都上传到服务器上时,然后向客户端发送 OK 响应,并在 OK 响应后合并相关内容。

这是我的代码:

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

您可以在操作后使用中间件进行处理 运行。

首先创建你的中间件

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>();