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

如何替换IndexOutOfRangeException错误并在c#中使用BadRequest()?,c#,asp.net-core,C#,Asp.net Core,在我的asp.net核心项目中,我有一个更新字符串字段的方法。我正在检查它是否是我需要显示错误的最后一个元素。但问题是我得到了预期的错误: System.IndexOutOfRangeException:索引超出了数组的界限。 我的方法如下: [HttpPost("upgradeproject/{userId}/{projectId}")] public async Task<IActionResult> UpgradeProject(int userId, int projectI

在我的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();
}
[HttpPost(“升级项目/{userId}/{projectId}”)]
公共异步任务升级项目(int userId,int projectId)
{
var projects=await\u context.projects.FirstOrDefaultAsync(x=>x.Id==
投射的);
var kube=wait_context.Kubesprays.Select(x=>x.Version.tolistSync();
字符串[]排序=kube
.OrderBy(item=>Version.Parse(Regex.Match)(item,@“[0-9]+(?:\[0-
9] +)+”.值)
.ToArray();
//var res=string.Join(Environment.NewLine,排序);
var currentVersion=projects.KubesprayTargetVersion;
var nextVersion=sorted[Array.IndexOf(sorted,currentVersion)+1];
var last=sorted.last();
如果(当前版本==上次)
{
return BadRequest(“您已经在使用最新版本”);//是否要
用这个
}
if(当前版本!=nextVersion)
{
返回错误请求(“升级已在进行”);
}
if(userId!=int.Parse(User.FindFirst(ClaimTypes.NameIdentifier.Value))
未经授权返回();
如果(当前版本==nextVersion)
{
projects.KubesprayTargetVersion=nextVersion;
//更新DbSet中的实体
_上下文。项目。更新(项目);
wait_context.SaveChangesAsync();
}
返回Ok();
}

这将满足您的要求:

try
{
    // Whatever you are trying
}
catch (IndexOutOfRangeException)
{
    return BadRequest("Message");
}
但是最好通过编码来检查超出范围来防止异常。使用Linq: (跳过版本索引对应的项目数,如果有,则获取下一个)


我认为最好是重写代码而不出现异常,并以这样的方式进行检查:

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];

版本具有类型字符串。此代码无法正常工作此代码也无法正常工作
First()
将返回版本,而不是可枚举的版本。您可以跳过此版本的第一个字符,并在处理字符串时使用第二个已编辑的字符。上次编辑获取下一个版本或null:)
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];