如何在 ASP.NET Web API 中重置会话中的 cookie 值?

问题描述 投票:0回答:1

我有一个简单的端点,每当从客户端调用它时,它就会重置它的 cookie 值。我尝试了

Clear
中提供的
Remove(string key)
ISession
方法,但没有一个有效。当我检查浏览器 ---> 应用程序 ----> Cookies 时,它仍然具有相同的值。

我是否遗漏了任何内容,或者我需要执行其他操作来重置会话密钥值吗?

这是我的代码:

[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();
}
asp.net asp.net-web-api session-cookies
1个回答
0
投票

您可以使用

Response.Cookies.Delete
。需要注意的是,修改服务器端的会话 cookie 不会自动更新客户端的浏览器。仅当响应返回到浏览器时,客户端才会收到更新的会话 cookie。另外,您可以检查此链接

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

// Set a new session cookie with the generated value
HttpContext.Session.SetString(sessionKey, value);
© www.soinside.com 2019 - 2024. All rights reserved.