在用户角色建立之前登录后重定向ASP.NET身份

时间:2017-08-22 07:56:05

标签: c# asp.net redirect asp.net-identity-2

我的登录信息几乎是身份标准代码。我添加了一些东西来做我需要的东西但是大多数情况下登录代码仍未编辑:

main

我修改了var result = signinManager.PasswordSignIn(User.UserName, Password.Text, RememberMe.Checked, shouldLockout: false); switch (result) { case SignInStatus.Success: // Store the user's supplier Id (if it exists - i.e. user is not an admin). using (ApplicationDbContext Context = new ApplicationDbContext()) { Session["UserId"] = User.Id; } IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); break; } 中的重定向,以根据用户的角色将用户带到这里或那里:

IdentityHelper

问题是,我第一次使用新用户登录(即我以管理员身份登录,注销并尝试以供应商身份登录),登录不会重定向,因为public static void RedirectToReturnUrl(string returnUrl, HttpResponse response) { if (!String.IsNullOrEmpty(returnUrl) && IsLocalUrl(returnUrl)) { response.Redirect(returnUrl); } else { if (HttpContext.Current.User.IsInRole("Supplier")) response.Redirect("~/Members/Supplier.aspx"); if (HttpContext.Current.User.IsInRole("Admin")) response.Redirect("~/Members/Admin.aspx"); if (HttpContext.Current.User.IsInRole("Consultant")) response.Redirect("~/Members/Consultant.aspx"); } } 返回false。

如果我立即使用相同的登录凭据再次尝试,它的效果非常好,所以在我看来系统正在尝试重定向太快而且登录实际上没有正确编译用户信息。

如果是这种情况,那么降低速度的最佳方法是什么才能在用户正确分配后才尝试重定向?

我觉得简单的HttpContext.Current.User.IsInRole("Supplier")循环可能效果不错:

do...while

虽然看起来有点hackish ......

1 个答案:

答案 0 :(得分:0)

身份信息存储在cookie中。在您的方案中,cookie尚未创建,因此using (MemoryStream memory = new MemoryStream()) { bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp); memory.Position = 0; BitmapImage bitmapimage = new BitmapImage(); bitmapimage.BeginInit(); bitmapimage.StreamSource = memory; bitmapimage.CacheOption = BitmapCacheOption.OnLoad; bitmapimage.EndInit(); return bitmapimage; } 不包含身份信息。

拥有HttpContext.Current.User循环无法解决您的问题。

使用userId从数据库获取用户角色和相关数据,并根据角色重定向用户,而不是尝试从do while获取。

您可以使用HttpContext来实现此目的。