redirect to return url after login

后端 未结 4 684
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 17:12

I have a link in my razor view like this:

  disputes

Inside my login\'s act

4条回答
  •  伪装坚强ぢ
    2020-12-05 17:56

    I use a combination of the above suggestion and Request.UrlReferrer to get the previous location:

        public ActionResult LogOn(string returnUrl)
        {
            //So that the user can be referred back to where they were when they click logon
            if (string.IsNullOrEmpty(returnUrl) && Request.UrlReferrer != null)
                returnUrl = Server.UrlEncode(Request.UrlReferrer.PathAndQuery);
    
            if (Url.IsLocalUrl(returnUrl) && !string.IsNullOrEmpty(returnUrl))
            {
                ViewBag.ReturnURL = returnUrl;
            }
            return View();
        }
    

    This way I don't have to put the location in the ActionLink.

    I populate a hidden field in the login page using the ViewBag.ReturnURL. Then in the Login HTTPPost ActionResult I redirect the user to the location in the hidden field (if there is one):

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            //returnURL needs to be decoded
            string decodedUrl = "";
            if (!string.IsNullOrEmpty(returnUrl))
                decodedUrl = Server.UrlDecode(returnUrl);
    
            //Login logic...
    
            if (Url.IsLocalUrl(decodedUrl))
            {
                return Redirect(decodedUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
    

提交回复
热议问题