具有不同路径值的 Cookie 在 Request.Cookie 中不存在
本文关键字:Cookie Request 不存在 路径 | 更新日期: 2023-09-27 18:30:18
我正在创建一个旧ASP Web应用程序的MVC版本,我需要重用现有的cookie,以便用户不必在MVC版本中重新配置他们的设置。大多数 Cookie 的路径值为/,但其他 Cookie 的路径值为/scripts。具有/scripts 路径值的那些不包含在 Request.Cookie 中。
谁能知道我如何访问和更新控制器中的/scripts cookie?顺便说一下,我对MVC相当陌生。
理想情况下,我想要一个服务器端解决方案,但如果不可能,那么客户端解决方案应该是可行的。
谢谢
对于那些想知道为什么 POST 请求在 c# 服务器端没有您的 cookie 的人。Cookie 相对于给定的路径存储,并且只能在请求任何子路径中看到该 Cookie。
因此,如果我的页面有路由[Route("/Home/Dashboard/{id:int}")]
则 AJAX 请求也需要相对于该路由。
例如
JavaScript:
// Set the Cookie
$.post("/Home/Dashboard/1/SaveMyThing", { myValue: "myValue" });
// Get the Cookie
$.post("/Home/Dashboard/1/DoMyThing");
C# (.NET CORE 3.1)
[HttpPost]
[Route("/Home/Dashboard/{id:int}/SaveMyThing")]
public ActionResult SaveMyThing(int id, string myValue) {
Response.Cookies.Append("myKey", myValue, new CookieOptions {
Path = $"/Home/Dashboard/{id}"
});
return Ok();
}
[HttpPost]
[Route("/Home/Dashboard/{id:int}/DoMyThing")]
public ActionResult DoMyThing(int id) {
ProcessMyThing(Request.Cookies["myKey"]);
return Ok();
}
Server Side code to Get and Set Cookies :
public void SetCookie(string key, string value, TimeSpan expires)
{
var encodedCookie = new HttpCookie(key, value);
encodedCookie.HttpOnly = true;
if (HttpContext.Current.Request.Cookies[key] != null)
{
var cookieOld = HttpContext.Current.Request.Cookies[key];
cookieOld.Expires = DateTime.Now.Add(expires);
cookieOld.Value = encodedCookie.Value;
HttpContext.Current.Response.Cookies.Add(cookieOld);
}
else
{
encodedCookie.Expires = DateTime.Now.Add(expires);
HttpContext.Current.Response.Cookies.Add(encodedCookie);
}
}
public string GetCookie(string key)
{
string value = string.Empty;
HttpCookie cookie = HttpContext.Current.Request.Cookies[key];
if (cookie != null)
{
// For security purpose, we need to encrypt the value.
HttpCookie decodedCookie = cookie;
value = decodedCookie.Value;
}
return value;
}
Client Side code to Get and Set cookies
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) != -1) {
return c.substring(name.length, c.length);
}
}
return "";
}