在我的 asp.net 核心项目中,我有更新字符串字段的方法。我正在检查它是否是我需要显示错误的最后一个元素。但问题是我收到了预期的错误: System.IndexOutOfRangeException:索引超出数组范围。
我的方法是这样的:
[HttpPost("upgradeproject/{userId}/{projectId}")]
public async Task<IActionResult> UpgradeProject(int userId, int projectId)
{
var projects = await _context.Projects.FirstOrDefaultAsync(x => x.Id ==
projectId);
var kube= await _context.Kubesprays.Select(x => x.Version).ToListAsync();
string[] sorted = kube
.OrderBy(item => Version.Parse(Regex.Match(item, @"[0-9]+(?:\.[0-
9]+)+").Value))
.ToArray();
//var res = string.Join(Environment.NewLine, sorted);
var currentVersion = projects.KubesprayTargetVersion;
var nextVersion = sorted[Array.IndexOf(sorted, currentVersion) + 1];
var last = sorted.Last();
if (currentVersion == last)
{
return BadRequest("You are already using the latest release"); // want to
use this
}
if (currentVersion != nextVersion)
{
return BadRequest("Upgrade already in progress");
}
if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
return Unauthorized();
if (currentVersion == nextVersion)
{
projects.KubesprayTargetVersion = nextVersion;
// Update entity in DbSet
_context.Projects.Update(projects);
await _context.SaveChangesAsync();
}
return Ok();
}
最佳答案
我认为重写代码而不获取异常并以这种方式检查它会更好:
var currentVersion = projects.KubesprayTargetVersion;
var currentVersionIndex = Array.IndexOf(sorted, currentVersion);
if (currentVersionIndex == sorted.Length - 1)
{
return BadRequest("You are already using the latest release");
}
var nextVersion = sorted[currentVersionIndex + 1];
关于c# - 如何替换 IndexOutOfRangeException 错误并在 C# 中使用 BadRequest() 代替?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60210591/