How to reset cookie value in a session in ASP.NET Web API?

24 Views Asked by At

I have a simple endpoint that will reset its cookie value whenever it is called from the client. I tried Clear and Remove(string key) method provided in the ISession but none are working. It is still having the same value when I inspect browser ---> Application ----> Cookies.

Am I missing anything or do I need to do anything else to reset the session key value ?

This is my code:

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
    var sessionKey = "MySessionKey";
    var value = GenerateRandomStr();

    HttpContext.Session.Remove(sessionKey); // does not work. Session cookie is not removed ?
    HttpContext.Session.Clear(); // does not work. Session cookie is not removed ?
    HttpContext.Session.SetString(sessionKey, value);  // since a random string is generated everytime this endpoint is called, I would expect it have a different cookie value in the session.           

    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray();
}
1

There are 1 best solutions below

0
Emre Akdemir On

You can use Response.Cookies.Delete. It's important to note that modifying the session cookie on the server side doesn't automatically update the client's browser. The client will only receive the updated session cookie when a response is returned to the browser. Also, you can examine this link

// Remove the existing session cookie
Response.Cookies.Delete(sessionKey);

// Set a new session cookie with the generated value
HttpContext.Session.SetString(sessionKey, value);