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); }
标签:
asp.net mvc
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!