c# - 如何替换 IndexOutOfRangeException 错误并在 C# 中使用 BadRequest() 代替?

标签 c# asp.net-core

在我的 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/

相关文章:

c# - 无法在对象中插入重复的键 - 如何在 Entity Framework Core 中创建复合键

visual-studio-2015 - 如何在 Visual Studio 测试中使用 ASP.NET Core 环境变量

c# - ASP.Net Core Web API - ICollection 未显示在 JSON 结果集中

c# - 仅针对特定用户的 Asp.net Core Windows 身份验证

c# - 使用 C# 创建 COM 扩展 - 值得吗?

c# - 如何使用 StructureMap 将属性注入(inject)自定义 ActionFilterAttribute?

c# - 如何使用 .NET 读取 ASP.NET 内部服务器错误描述?

c# - 使用 RabbitMQ 永不结束消息

c# - .net core 5 中具有参数依赖关系的全局过滤器

c# - 添加 Claims Transformer 后注入(inject)的 IPrincipal Claims 为空