这是(希望)这个不太广泛的版本:Show progress on long-running process
我在ASP.Net Core中有一个长期运行的任务,并且希望能够在不使用SignalR的情况下为该任务提供进度。
以下是端点示例:
[HttpGet]
[Route("/getter/world/{world}/cities")]
public async Task<IActionResult> GetCities(int world)
{
ApiGetter getter = new ApiGetter(_config);
try
{
//3rd party cookie
if (!await IsValidCookie(getter, world))
{
return BadRequest("Invalid Session");
}
IEnumerable<PlayerRank> rankings = await getter.GetWorldScoreRankings(world);
List<City> cities = new List<City>();
foreach (PlayerRank rank in rankings)
{
try
{
IEnumerable<City> playerCities = await getter.GetPlayerCities(rank, 5);
IEnumerable<City> uniqueCities = playerCities.GroupBy(c => c.CityID).Select(c => c.First()).ToList();
cities.AddRange(uniqueCities);
_repository.InsertCities(uniqueCities);
}
catch (DbUpdateException ex) when ((ex.InnerException as MySqlException)?.Number == 1062)
{
continue;
}
}
return Ok(cities.Count);
}
catch (DbUpdateException ex) when ((ex.InnerException as MySqlException)?.Number == 1062)
{
return BadRequest("City data already inserted for today");
}
}
这个端点正在管理多个事情,我知道没有关注SRP的问题。
尽量避免过于宽泛的问题&#34;旗帜,这是我想要解决的问题:
我需要知道的事情:
foreach
循环我不需要知道的事情:
由于我无法从GetCities()
方法返回多个时间,因此我假设我需要一个额外的端点,我可以调用它来检索当前进度。如果是这样,我如何以可供其他端点使用的方式记录该进度?
如果是简单/范围内可选:我如何确保只有启动任务的用户才能看到进度?
编辑:会话TempData是否适合此?将进度写入TempData,并进一步请求读取它?
答案 0 :(得分:1)
您的问题已涵盖基本&#34;如何获取长时间运行任务的状态&#34;所以我假设你做了关于简单解决方案的功课。
确保只有发起请求的客户端可以检查进度的一种方法是将客户端密钥传递给请求(客户端生成的字符串或数字)。这样,只有知道这个秘密,你才能检查进度。 这种方法的缺点如果客户端死了,它可能会失去这个秘密。
用那个&#34;客户秘密&#34;记住,让我们回答问题:
如何记录foreach循环的进度
使用客户端密钥跟踪创建进度图。使用某种地图(内存或redis)来映射sso >> r1 >> r2 >> r3;
。在每个for循环迭代中,更新映射并在一定时间后使条目无效。
如何根据要求将其返回给客户
让端点使用客户端密钥检查进度。
如何确保只有启动任务的用户才能看到进度?
客户端秘密解决了这个问题。