自定义角色提供程序不工作 - 登录后立即重定向到登录页面

Custom Role Provider not working - Instant redirect to login page after logging in

我做了一个自定义的角色提供者。在我更新我的 VS 和 NuGet 包之前,一切似乎都正常。但是,当我现在登录时,页面看起来会刷新(或者至少重新加载视图)。虽然我确实看到创建了一个 cookie,但我不会重定向到 Index。为什么?

在我的 Web.Config:

 <authentication mode="Forms">
      <forms loginUrl="~/Home/Login" timeout="2880" />
    </authentication>
<roleManager defaultProvider="MyRoleProvider">
      <providers>
        <add name="MyRoleProvider" type="project.Authorisation.CustomRoleProvider" />
        <remove name="MySQLRoleProvider" />
        <add name="MySQLRoleProvider" type="MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.9.6.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="LocalMySqlServer" applicationName="/" />
      </providers>
    </roleManager>

在我的 HomeController 中:

    public ActionResult Login()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Login(User user)
    {
        if (ModelState.IsValid)
        {
            bool authenticated = userDBController.isAuthorized(user.Nickname, user.Password);

            if (authenticated)
            {
                    FormsAuthentication.SetAuthCookie(user.Nickname, false);
                    return Redirect(Url.Action("Index", "Home"));
            }
            else
            {
                ViewBag.Message = "Inlog data is incorrect!";
                return View();
            }
        }
        else
        {
            return View();
        }
    }
    [Authorize(Roles = "ADMIN")]
    public ActionResult Index()
    {
        return View();
    }

所以当我登录时我不能去 Home/Index,它会重定向我到登录。登录后同理

我的自定义 RoleProvider 现在非常简单:

public class CustomRoleProvider : RoleProvider
{
    private MainController mainController = MainController.Instance;
    private UserDBController userDBController = MainController.Instance.GetUserDBController();

public override string[] GetRolesForUser(string username)
{
    return userDBController.getRollen(username);
}

在一切之前,这一切都有效(也是授权)。

好吧,我终于找到问题所在了!

显然是在重新安装软件包之后,我的 web.config 发生了变化。我所要做的就是将 enabled="true" 添加到 roleManager 部分。因此代码应该如下所示:

<roleManager defaultProvider="MyRoleProvider" enabled="true">
  <providers>
    <add name="MyRoleProvider" type="project.Authorisation.CustomRoleProvider" />
  </providers>
</roleManager>

看来角色管理器已被禁用。 我希望这会帮助其他可能遇到此问题的人!