简体   繁体   English

Asp.net无法获取更新的Cookie

[英]Asp.net Couldn't get the updated Cookies

Updating the desired functionality with Cookies as it has been implemented through sessions. 通过cookie更新所需的功能,因为它已通过会话实现。 In my scenario, i am adding/updating a Cookie in action method and when the partial view renders it gets the previous data of the cookie. 在我的场景中,我将在操作方法中添加/更新Cookie,并且当部分视图呈现时,它将获取Cookie的先前数据。 Once the page is reloaded only then it displays the updated data. 仅重新加载页面后,它将显示更新的数据。

Action Method 行动方法

Response.Cookies["TColumns"].Value = string.Join(",", displayListCol); ;
Response.Cookies["TColumns"].Expires = DateTime.Now.AddDays(10);
Response.Cookies["TColumns"].Domain = null;

Partial View 部分视图

<%
List<string> selectedColumns = Request.Cookies["TColumns"].Value.ToString().Split(',').ToList();
//Some code
%>

Followed these MSDN links to write and read cookies in asp.net application. 遵循这些MSDN链接在asp.net应用程序中写入读取 Cookie。

Thanks! 谢谢!

When you set a cookie, it actually adds a response header. 设置Cookie时,实际上会添加一个响应头。 When the client receives the response, and parses the headers, it creates the cookie locally. 当客户端收到响应并解析标头时,它将在本地创建cookie。 On the next request, the client will set a request header with the previously set cookie. 在下一个请求时,客户端将使用先前设置的cookie设置请求标头。 Only then is the cookie seen on the server. 只有这样才能在服务器上看到Cookie。

In your code, you're setting the cookie and trying to read it all in the same request. 在您的代码中,您正在设置cookie并尝试在同一请求中全部读取它。 The cookie has not been set yet, so you cannot read it yet. 该cookie尚未设置,因此您无法阅读。 There must be a new request made by the client before the cookie will be able to be read. 客户端必须发出一个新请求,才能读取Cookie。 This is why your code works once the page is refreshed. 这就是刷新页面后代码可以工作的原因。 A quick way to avoid having to manually refresh the page is to redirect after setting the cookie. 避免手动刷新页面的一种快速方法是在设置cookie后进行重定向。 Regardless of how you handle it, you need another request to read the cookie after setting it. 无论如何处理,设置后都需要另一个请求来读取Cookie。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM