[c#] Using Cookie in Asp.Net Mvc 4

I have web application in Asp.Net MVC4 and I want to use cookie for user's login and logout. So my actions as follows:

Login Action

    [HttpPost]
    public ActionResult Login(string username, string pass)
    {
        if (ModelState.IsValid)
        {
            var newUser = _userRepository.GetUserByNameAndPassword(username, pass);
            if (newUser != null)
            {
                var json = JsonConvert.SerializeObject(newUser);

                var userCookie = new HttpCookie("user", json);
                userCookie.Expires.AddDays(365);
                HttpContext.Response.Cookies.Add(userCookie);

                return RedirectToActionPermanent("Index");
            }
        }
        return View("UserLog");
    }

LogOut Action

    public ActionResult UserOut()
    {
        if (Request.Cookies["user"] != null)
        {
            var user = new HttpCookie("user")
                {
                    Expires = DateTime.Now.AddDays(-1),
                    Value = null
                };
            Response.Cookies.Add(user);
        }
        return RedirectToActionPermanent("UserLog");
    }

And I use this cookie in _Loyout as follow:

@using EShop.Core
@using Newtonsoft.Json
@{
   var userInCookie = Request.Cookies["user"];
}
...
  @if (userInCookie != null && userInCookie.Value)
  {
        <li><a href="#">Salam</a></li>
        <li><a href="@Url.Action("UserOut", "Home")">Cixis</a></li>
  }
  else
  {
        <li><a href="@Url.Action("UserLog", "Home")">Giris</a></li>
  }

But When I click *UserOut* action this action happen first time, but then it doesn't work. I put breakpoint for looking process but it get UserLog action doesn't UserOut. My question is that where I use wrong way of cookie? What is a best way using cookie in Asp.Net Mvc4 for this scenario ?

This question is related to c# asp.net-mvc-4 cookies action httpcookie

The answer is


We are using Response.SetCookie() for update the old one cookies and Response.Cookies.Add() are use to add the new cookies. Here below code CompanyId is update in old cookie[OldCookieName].

HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name.
cookie.Values["CompanyID"] = Convert.ToString(CompanyId);
Response.SetCookie(cookie); //SetCookie() is used for update the cookie.
Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.

userCookie.Expires.AddDays(365); 

This line of code doesn't do anything. It is the equivalent of:

DateTime temp = userCookie.Expires.AddDays(365); 
//do nothing with temp

You probably want

userCookie.Expires = DateTime.Now.AddDays(365); 

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc-4

Better solution without exluding fields from Binding How to remove error about glyphicons-halflings-regular.woff2 not found When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 How to get DropDownList SelectedValue in Controller in MVC Return HTML from ASP.NET Web API There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country Return JsonResult from web api without its properties how to set radio button checked in edit mode in MVC razor view How to call MVC Action using Jquery AJAX and then submit form in MVC?

Examples related to cookies

SameSite warning Chrome 77 How to fix "set SameSite cookie to none" warning? Set cookies for cross origin requests Make Axios send cookies in its requests automatically How can I set a cookie in react? Fetch API with Cookie How to use cookies in Python Requests How to set cookies in laravel 5 independently inside controller Where does Chrome store cookies? Sending cookies with postman

Examples related to action

Adding form action in html in laravel How to set the action for a UIBarButtonItem in Swift Execution order of events when pressing PrimeFaces p:commandButton Using Cookie in Asp.Net Mvc 4 Get controller and action name from within controller? HTML form action and onsubmit issues How to pass value from <option><select> to form action Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id} Single line if statement with 2 actions How do I use two submit buttons, and differentiate between which one was used to submit the form?

Examples related to httpcookie

Using Cookie in Asp.Net Mvc 4