You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google API登录后跳转页面出现Index out of range错误求助

排查并修复索引超出范围错误

老哥,你碰到的Index out of range错误原因特别直观:当你调用UserManager.GetRoles(user.GetUserId())时,如果当前登录用户没有被分配任何角色,返回的角色集合就是空的,这时候你直接去取集合的第一个元素s[0],自然就会触发索引越界的问题。

咱们可以通过两个简单的调整来解决这个问题,同时让逻辑更健壮:

  • 先判断角色集合是否有元素,避免直接访问不存在的索引
  • 改用更合理的方式判断用户是否拥有Admin角色(不需要硬取第一个元素)

修改后的完整代码如下:

if (User.Identity.IsAuthenticated) 
{ 
    var user = User.Identity; 
    ApplicationDbContext context = new ApplicationDbContext(); 
    var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); 
    var roles = UserManager.GetRoles(user.GetUserId()); 
    
    // 直接判断集合是否包含Admin角色,空集合会自动返回false
    return roles.Contains("Admin"); 
}
// 补充未认证时的返回逻辑,比如:
return false;

额外提两个小建议:

  1. 尽量不要在方法里直接new ApplicationDbContext和UserManager,可以用依赖注入的方式获取,避免资源泄漏和代码耦合
  2. 上面的代码已经简化了逻辑——roles.Contains("Admin")在空集合时会直接返回false,不需要额外判断集合是否为空,代码更简洁

内容的提问来源于stack exchange,提问作者Huy Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:29:19