ASP.NET MVC重定向到目标页面或登录后重定向到上一页

时间:2015-05-23 08:20:18

标签: asp.net-mvc

我使用asp.net MVC时遇到以下问题:当管理员更新用户请求时,他将收到一封电子邮件,告知该请求已更新,并且在此电子邮件中将显示指向该页面的链接{{ 1}}。

要访问该页面,用户必须登录,以便链接重定向到登录页面。登录后,用户被重定向到http://www.domain.com/request, 登录后如何重定向到电子邮件发送的地址?

http://www.domain.com/welcome

我尝试了这个但是没有工作:

[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl, bool createPersistentCookie)
{
    // Check if the Model is valid or not
    if (ModelState.IsValid)
    {
        using (GNEntities entities = new GNEntities())
        {
            string username = model.Email;
            string password = model.Password;

            // Now if our password was enctypted or hashed we would have done the
            // same operation on the user entered password here, But for now
            // since the password is in plain text lets just authenticate directly


            bool userValid = entities.Employee.Any(user => user.Email == username && user.Password == password && user.IsActive ==true);

            // User found in the database
            if (userValid)
            {

                FormsAuthentication.SetAuthCookie(username, createPersistentCookie); //false:not persistent cookie

                Employee e = (Employee)entities.Employee.FirstOrDefault(user => user.Email == username);


                if (e.Roles.Id==1 || e.RoleId == 3) // 3 = commercial
                {
                    return RedirectToAction("Index", "AdminIndex", new { Area = "AdminArea" });
                }
                else if (e.Roles.Id == 2 || e.Roles.Id ==4)
                {
                    int countryId = e.CountryId;
                    return RedirectToAction("Index", "Calendar", new { year = DateTime.Now.Year, countryId, Area = "EmpArea" });//with paramenters RedirectToAction("Index", new { id = currentcoupon.Companyid.id, Area="Admin" });
                }
            }
            else
            {
                ModelState.AddModelError("", "The email or password provided is incorrect or your account has been disabled.");
            }
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);

结果仍然不好: 这是登录前的网址if (returnUrl == null) { int countryId = e.CountryId; return RedirectToAction("Index", "Calendar", new { year = DateTime.Now.Year, countryId, Area = "EmpArea" }); } else { return RedirectToAction(returnUrl, new {Area = "EmpArea"}); }

并在登录后生成此网址domain.net/Login/Login?ReturnUrl=%2fEmpArea%2fTimesheet

它保留了登录区域,我不知道为什么。

1 个答案:

答案 0 :(得分:0)

在您的登录代码中,成功验证凭据后,您将用户重定向到AdminIndexCalendar。请注意,Login操作有一个returnUrl参数可供您使用。

因此,在您成功登录后,检查参数是否为空,并{}将用户redirect指向该网址:

if(!string.IsNullOrEmpty(returnUrl))
    return Redirect(returnUrl);
相关问题