Malik Kashmiri Malik Kashmiri -4 years ago 186
C# Question

Cookies in ASP.Net MVC 5

I am developing an application in which users are SignUp or SignIn by External Identity Providers like AAD, Google, WS-Federated Authentication etc. Now I want to create cookies on a user machine to logged in until user SignOut. Give me some thought and guide me how I can overcome it. thanks in advance.

Answer Source

Use Request.Cookies and Response.Cookies to handle your situation. once user coming back from third party authorization create cookie and store it in browser and once user Logout clear the cookie.

 string cookievalue ;
 if ( Request.Cookies["cookie"] != null )
 {
    cookievalue = Request.Cookies["cookie"].ToString();
 }
 else
 {
    Response.Cookies["cookie"].Value = "cookie value";
 }

For removing cookie use following code

if (Request.Cookies["cookie"] != null)
{
    Response.Cookies["cookie"].Expires = DateTime.Now.AddDays(-1);   
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download