gpt4 book ai didi

c# - 根据 ASP.NET MVC 4 Internet 应用程序登录中的用户角色重定向到不同的页面

转载 作者:行者123 更新时间:2023-11-30 12:44:29 25 4
gpt4 key购买 nike

我正在创建 ASP.NET MVC 4 Internet 应用程序。在那个应用程序中我创建了任何用户都可以登录的登录页面,然后我尝试根据用户的角色将用户重定向到不同的页面。

ASP.NET Identity 是这里的成员系统。

在我的 AspNetRoles 表中,我有两个角色:

Id| Name

1 | HEI_Admin

2 | HEI_User

这是我的登录 Controller 方法:

    [HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);

if (user != null)
{
if (user.ConfirmedEmail == true)
{

await SignInAsync(user, model.RememberMe);

if (String.IsNullOrEmpty(returnUrl))
{
if (UserManager.IsInRole(user.Id, "HEC_Admin"))
{
return RedirectToAction("Index", "HEC");
}
//role Admin go to Admin page
if (UserManager.IsInRole(user.Id, "HEI_User"))
{
return RedirectToAction("Index", "HEI");
}
}

else
{
return RedirectToLocal(returnUrl);
}


}
else
{
ModelState.AddModelError("", "Confirm Email Address.");
}
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}

但是当我尝试使用正确的凭据登录时,出现以下错误:

建立与 SQL Server 的连接时出现与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。

所有连接都经过双重检查,如何实现这个问题。

最佳答案

        if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
if (UserManager.IsInRole(user.Id, "Admin"))
{
return RedirectToAction("Index", "Admin");
}
else if (UserManager.IsInRole(user.Id, "Clerk"))
{
return RedirectToAction("Index","Employee");
}
else if (UserManager.IsInRole(user.Id, "Customer"))
{
return RedirectToAction("Index", "Customer");
}
//return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("","Invalid username or password");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}

这是我用于重定向的代码。还要查看userID 和RoleID 是否插入到ASPNETUserRoles 表中

关于c# - 根据 ASP.NET MVC 4 Internet 应用程序登录中的用户角色重定向到不同的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28358506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com