在MVC Controller中的ReturnRedirectToAction的情况下调用Dispose方法

时间:2018-03-21 06:37:09

标签: c# asp.net-mvc asp.net-identity

我正在使用MVC,但我遇到了一个调用dispose方法的问题。当我要登录时,所有验证和登录都正常工作但是当我在成功登录后重定向时,在返回重定向到操作的情况下,正在调用dispose方法。 我该怎么办? 这是我的控制器:

 public UserManager<ApplicationUser> UserManager { get; private set; }

    public AdminController()
        : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
    {

    }

    public AdminController(UserManager<ApplicationUser> userManager)
    {
        UserManager = userManager;
    }

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginViewModel model, string returnUrl)
    {
        if (Session["RoleID"] != null)
        {
            if (Convert.ToInt32(Session["RoleID"]) == Ansits2018.UTILITIES.Constants.Admin)
            {
                return RedirectToAction("Index", "Admin");
            }
        }
        if (ModelState.IsValid)
        {
            var accRepo = new AccountRepository();
            int UserID = 0;
            UserID = accRepo.IsUserValid(model.UserName, model.Password);

            if (UserID > 0)
            {
                var user = accRepo.GetUserByUsername(model.UserName);
                Session["CompanyID"] = 1;
                Session["UserID"] = UserID;
                Session["Username"] = model.UserName;
                Session["RoleID"] = user.RoleID;
                Session["Name"] = user.Name;
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                                                   1,                                   // ticket version
                                                   user.Username,  // authenticated username
                                                   DateTime.Now,                        // issueDate
                                                   DateTime.Now.AddMinutes(60),        // expiryDate
                                                   true,                                // true to persist across browser sessions
                                                   user.RoleID.ToString(),       // can be used to store additional user data
                                                   FormsAuthentication.FormsCookiePath  // the path for the cookie
                                                   );

                // Encrypt the ticket using the machine key
                string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                // Add the cookie to the request to save it
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                cookie.HttpOnly = true;
                Response.Cookies.Add(cookie);
                if (!String.IsNullOrEmpty(returnUrl))
                {
                    return RedirectToLocal(returnUrl);
                }
                if (user.RoleID == Ansits2018.UTILITIES.Constants.Admin)
                {
                    return RedirectToAction("Index", "Admin");
                }
            }
            else
            {
                TempData["Message"] = "Invalid username or password.";
                return View(model);
            }
        }
        // If we got this far, something failed, redisplay form
        return View(model);
    }

  protected override void Dispose(bool disposing)
    {
        if (disposing && UserManager != null)
        {
            UserManager.Dispose();
            UserManager = null;
        }
        base.Dispose(disposing);
    }

1 个答案:

答案 0 :(得分:0)

RedirectToAction(至少你正在使用的形式)构造如下:

RedirectToAction(string actionName, string controllerName)

因此return RedirectToAction("Index", "Home");将您带到主控制器中的索引操作,return RedirectToAction("Index", "Admin");将您带到管理控制器的索引操作。

因此,如果我正确阅读您的问题,您需要将代码更改为return RedirectToAction("Index", "Home");

更新(根据评论):

如果您想要RedirectToAction("Index", "Admin");,那么您需要调试代码以找出问题所在。您可以为调试设置断点,或将这些调试行添加到代码中:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
    if (Session["RoleID"] != null)
    {
        if (Convert.ToInt32(Session["RoleID"]) == Ansits2018.UTILITIES.Constants.Admin)
        {
            return RedirectToAction("Index", "Admin");
        }
    }

    if (ModelState.IsValid)
    {
        var accRepo = new AccountRepository();
        int UserID = 0;
        UserID = accRepo.IsUserValid(model.UserName, model.Password);

        if (UserID > 0)
        {
            var user = accRepo.GetUserByUsername(model.UserName);
            Session["CompanyID"] = 1;
            Session["UserID"] = UserID;
            Session["Username"] = model.UserName;
            Session["RoleID"] = user.RoleID;
            Session["Name"] = user.Name;
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                                                1,                                   // ticket version
                                                user.Username,  // authenticated username
                                                DateTime.Now,                        // issueDate
                                                DateTime.Now.AddMinutes(60),        // expiryDate
                                                true,                                // true to persist across browser sessions
                                                user.RoleID.ToString(),       // can be used to store additional user data
                                                FormsAuthentication.FormsCookiePath  // the path for the cookie
                                                );

            // Encrypt the ticket using the machine key
            string encryptedTicket = FormsAuthentication.Encrypt(ticket);
            // Add the cookie to the request to save it
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            cookie.HttpOnly = true;
            Response.Cookies.Add(cookie);
            if (!String.IsNullOrEmpty(returnUrl))
            {
                System.Diagnostics.Debug.WriteLine("1 #####> RedirectToLocal (valid Login): " + returnUrl);
                return RedirectToLocal(returnUrl);
            }
            if (user.RoleID == Ansits2018.UTILITIES.Constants.Admin)
            {
                return RedirectToAction("Index", "Admin");
            }
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("2 #####> Invalid Login Attempt - UserID > 0: " + model.UserName + " => " + model.Password));
            TempData["Message"] = "Invalid username or password.";
            return View(model);
        }
    }

    System.Diagnostics.Debug.WriteLine("3 #####> ModelState Invalid: " + model.UserName + " => " + model.Password);
    return View(model);
}

然后单击Login View Action(而不是[HttpPost])上的光标,在菜单中单击Debug,然后单击Start Debugging。等待所有人安顿下来然后登录并观看调试消息以查看出现的消息。这应该给出了什么是错误的,以及你需要做什么的好线索。