根据返回的switch语句中的用户角色返回RedirectToAction()Views()的

问题描述:

在用户成功登录后,我希望页面根据用户角色重定向到合适的页面。我有一些代码工作,它允许我从登录凭证中检索和检查用户角色,但switch语句不允许我使用if-else语句。根据返回的switch语句中的用户角色返回RedirectToAction()Views()的

它希望我返回一个View(),但我总是重定向到Home/Index视图。这里是我的代码:

 switch (result) 
     { 

      case SignInStatus.Success: 
       MigrateShoppingCart(model.Email); 
       //returnURL needs to be decoded 
       string decodedUrl = ""; 
       if (!string.IsNullOrEmpty(returnUrl)) 
        decodedUrl = Server.UrlDecode(returnUrl); 

       if (Url.IsLocalUrl(decodedUrl)) 
       { 
        return Redirect(decodedUrl); 
       } 

       string id = UserManager.FindByEmail(model.Email).Id; 
       IList<string> roleNames = UserManager.GetRoles(id); 

       if (roleNames.Contains("Admin")) 
       { 
        RedirectToAction("Index", "Category"); 
       } 
       else 
       { 
        return RedirectToAction("Index", "Home"); 
       } 
       return View(); 
      case SignInStatus.LockedOut: 
       return View("Lockout"); 
      case SignInStatus.RequiresVerification: 
       return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); 
      case SignInStatus.Failure: 
      default: 
       ModelState.AddModelError("", "Invalid login attempt."); 
       return View(model); 
     } 
+1

错误信息是什么? –

+0

即使用户具有“管理员”角色,我也总是被重定向到“家庭/索引”视图。 – naz786

+1

如果之前可以共享角色名称的值吗? –

它在我的代码是一个小错误,因为我并没有在第一,如果情况使用return字。更改此代码:

if (roleNames.Contains("Admin")) 
{ 
    RedirectToAction("Index", "Category"); 
} 
else 
{ 
    return RedirectToAction("Index", "Home"); 
} 
return View(); 
case SignInStatus.LockedOut: 
return View("Lockout"); 

要这样:

if (roleNames.Contains("Admin")) 
{ 
    return RedirectToAction("Index", "Category"); 
} 
else 
{ 
    return RedirectToAction("Index", "Home"); 
} 

case SignInStatus.LockedOut: 
return View("Lockout"); 

通知我也能够去除return view()代码。