URL FormsAuthentication. RedirectFromLoginPage, mvcredirect
In traditional Asp.net webForm, if Form authentication is used. You only need to use
FormsAuthentication.RedirectFromLoginPage
But in MVC, MVC does not need this one. I tried a lot of methods. But it was done in the end. The reason why "FormsAuthentication. RedirectFromLoginPage" is written in the title ". It was because I kept searching for the keyword "FormsAuthentication. RedirectFromLoginPage" in Google at the beginning to find out how to apply this keyword to MVC. Or is there any alternative method in MVC. Failed but inspired.
Because no logon user will be redirected to the logon page if the logon page is not accessed directly. In addition, the URL will follow the ReturnUrl parameter record from which the page is redirected.
So we can do this
1. Receive the "ReturnUrl" parameter in the "Action" method of logon.
2. Verify that the logon is successful in the "Action" method. If "ReturnUrl" is not blank, the page directed to "ReturnUrl" is displayed.
Code:
1. entity:
The "ReturnUrl" parameter is added to the logon entity to receive the page address before logon.
public class LoginInfo { public string LoginName { get; set; } public string LoginPwd { get; set; } public string SecurityCode { get; set; } public string ReturnUrl { get; set; } }
2. logon page Action
[AllowAnonymous] public ActionResult Login(string returnUrl) { ViewBag.returnUrl = returnUrl; return View(); }
3. logon page view
Auxiliary method "@ Html. hidden ("returnUrl") automatically generates the "<input id =" returnUrl "name =" returnUrl "type =" hidden ">" HTML code and binds the "ViewBag. returnUrl "attribute.
<Form action = "/User/Login" method = "post"> <input type = "text" name = "LoginName"/> <input type = "password" name =" loginPwd "/> <input type =" text "name =" SecurityCode "/> <a href =" javascript: void (0 ); "onclick =" refreshCode () "> refresh </a> <input type =" submit "value =" Logon "/>@ Html. Hidden ("returnUrl ")</Form>
4. Execute the login verification Action
[HttpPost] [AllowAnonymous] public void Login (LoginInfo login) {if (login. SecurityCode! = SessionUtil. authenticationCode) throw new BusinessException ("Verification code error"); 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"); elseResponse. Redirect (login. ReturnUrl );}