我正在使用 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);
}
}
uj5u.com熱心網友回復:
您可以在操作運行后使用中間件進行處理。
首先創建你的中間件
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>();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/470991.html
標籤:网 asp.net 核心 .net-core asp.net-web-api
上一篇:訪問Microsoft.Extensions.Hosting服務時出錯。添加ASP.NET標識后
下一篇:C#LINQ過濾子表中的記錄
