如何在ASP中向客户端返回OK响应后调用其他方法.净的核心



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

问题是当我上传一个巨大的文件,然后我得到一个很长一段时间后的响应。所以我想做的是当所有的块上传到服务器上,然后发送一个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
}
}
}

使用中间件

app.UseMiddleware<UploadMiddleware>();

相关内容

最新更新