1.在登录的“Action” 方法中接收“ReturnUrl”参数。

2.在验证登录的“Action”方法中登录成功后,判断如果“ReturnUrl”不为空就跳转到“ReturnUrl”指向的页面。

代码:

1.实体:

在登录的实体中增加了“ReturnUrl”参数用于接收登录前的页面地址

    public class LoginInfo
    {
        public string LoginName { get; set; }

        public string LoginPwd { get; set; }

        public string SecurityCode { get; set; }

        public string  ReturnUrl { get; set; }
    }

2.登录页面的Action

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.returnUrl = returnUrl;

            return View();
        }

3.登录页面视图

辅助方法“@Html.Hidden("returnUrl")”会自动的生成“<input id="returnUrl" name="returnUrl" type="hidden">”HTML代码,并且绑定“ViewBag.returnUrl”属性。
<form action="/User/Login" method="post">
    <input type="text" name="LoginName" />
    <input type="password" name="LoginPwd" />
    <input type="text" name="SecurityCode" />
    <img id="veri_code" src="@Url.Action("AuthenticationCode", new { r = new Random().NextDouble() })" width="65" height="23" class="identify_code" alt="验证码" />
    <a href="javascript:void(0);" onclick="refreshCode()">刷新</a>
    <input type="submit" value="登录" />
    @Html.Hidden("returnUrl")
</form>

4.执行登录验证的Action

        [HttpPost]  //只接受Post方式的请求
        [AllowAnonymous]   
        public void Login(LoginInfo login)
        {
            if (login.SecurityCode != SessionUtil.AuthenticationCode)
                throw new BusinessException("验证码错误");

            var user = UserService.Instance.Login(login.LoginName, login.LoginPwd);
            SessionUtil.Current = user;

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1, user.Id.ToString(), DateTime.Now, DateTime.Now.AddYears(1),
            true, string.Empty, FormsAuthentication.FormsCookiePath);

            string ticString = FormsAuthentication.Encrypt(ticket);

            HttpCookie coo = new HttpCookie(FormsAuthentication.FormsCookieName, ticString);

            if (ticket.IsPersistent)
            {
                coo.Expires = ticket.Expiration;
            }
            
            Response.Cookies.Add(coo);if (string.IsNullOrWhiteSpace(login.ReturnUrl))
                Response.Redirect("/PublicAccountWater/Index");
            else
                Response.Redirect(login.ReturnUrl);
        }