i want make login , logout functions in mvc4. in login func, if login cookie exist , not empty, user in signin mode, else redirect login page. in logout func, cookies , sessions clear , redirect login func, in login func login cookie exist!
login:
public actionresult login() { if (request.cookies["login"] != null) { string login = request.cookies["login"].value.tostring(); if (login != string.empty) { //get service service srv = new service(); useritem useritem = srv.getuseritem(login); srv.close(); session.timeout = 30; session["login "] = login; session["userid"] = useritem.no; session["firstname"] = useritem.firstname; session["lastname"] = useritem.lastname; string loginname = useritem.loginname; formsauthentication.setauthcookie(loginname, false); return redirect(“index”); } else { return redirect("http://mysite/signin.aspx"); } } else { return redirect("http://mysite/signin.aspx"); } }
logout:
public actionresult logout() { string login = session["login"].tostring(); request.cookies["login"].value = ""; response.cookies["login"].value = ""; formsauthentication.signout(); httpcookie c = request.cookies[formsauthentication.formscookiename]; c.expires = datetime.now.adddays(-1); session.clear(); request.cookies.clear(); response.cookies.clear(); //formsauthentication.initialize(); //string strrole = string.empty; //formsauthenticationticket fat = new formsauthenticationticket(1, "", datetime.now, datetime.now.addminutes(-30), false, strrole, formsauthentication.formscookiepath); //response.cookies.add(new httpcookie(formsauthentication.formscookiename, formsauthentication.encrypt(fat))); //session.abandon(); //// clear authentication cookie //httpcookie cookie1 = new httpcookie(formsauthentication.formscookiename, ""); //cookie1.expires = datetime.now.addyears(-1); //response.cookies.add(cookie1); //// clear session cookie (not necessary current problem recommend anyway) //httpcookie cookie2 = new httpcookie("asp.net_sessionid", ""); //cookie2.expires = datetime.now.addyears(-1); //response.cookies.add(cookie2); //formsauthentication.redirecttologinpage(); return redirecttoaction("login", "usr"); }
web.config:
<authentication mode="forms"> <forms loginurl="~/usr/login" timeout="30" /> </authentication>
i trying comment codes, comment line:
formsauthentication.signout();
even set cookie value "", in login page cookie have old value! , trying several ways clear cookie set expire 1 day later. but…
thanks
you're changing value of cookie, you're not adding response again!
formsauthentication.signout(); httpcookie c = request.cookies[formsauthentication.formscookiename]; c.expires = datetime.now.adddays(-1); // update amended cookie! response.cookies.set(c) session.clear(); /* rid of this, break above clearing * cookie collection you've updated. */ // request.cookies.clear(); // response.cookies.clear();
Comments
Post a Comment