Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a cookie at the click of logout in Asp.Net MVC3

I have a asp.net MVC3 Application with two users Admin and General.Cookies is saved for both the users. Below is how my cookies is saved.

 Cookie.setCookie(No,DOB,User); 

Have a class Cookie with the method setCookie

 public static void setCookie(int No,DateTime DOB,string User)
        {
            HttpCookie MyCookie= new HttpCookie("MyCookie");
            MyCookie["No"] = No;
            MyCookie["DOB"] = DOB;
            MyCookie["User"] = User;

            MyCookie.Expires.Add(new TimeSpan(0,30,0));

            HttpContext.Current.Response.Cookies.Add(MyCookie);
        }

Above is my Setcookie code.

MyCookie.Expires.Add(new TimeSpan(0,30,0));will give the default expiry time to 30 minutes.

What im trying is when the user click Logout the cookie should get completely cleared and the user should not be able to navigate to any of the Authenticated sections of the site. Also i have tried this but no use

MyCookie.Expires.Add(-1);

But i have tried that in my SetCookie method.How can i make the cookies cleared when the user clicks Logout. Also i have tried creating a Logout Method in Cookie Class like below:

  public static bool logout()
        {

            HttpCookie reqCookies = HttpContext.Current.Request.Cookies["MyCookie"];
            reqCookies.Expires.AddDays(-1);
            return true;
        }

Here im Trying to use the already saved cookie and Expire it by setting .AddDays(-1); And im using if cookie.Logout()==true and redirecting it to my Home. But it is giving me following error on RunTime The added or subtracted value results in an un-representable DateTime. Parameter name: value

Any suggestions/guidance on how can i achieve my target.

like image 326
Sam M Avatar asked Dec 10 '11 06:12

Sam M


2 Answers

To clear a cookie in ASP.NET, you need to set a new cookie with the same name with an expired time.

like image 167
Jeffrey Zhao Avatar answered Oct 24 '22 05:10

Jeffrey Zhao


You can use a jquery cookie script for that.

<a href="" onclick="removeCookie();">logout button</a>

function removeCookie(){
$.cookie('cookiename', '');
}
like image 21
bobek Avatar answered Oct 24 '22 05:10

bobek