我正在创建一个旧的ASP Web应用程序的MVC版本,我需要重用现有的cookie,以便用户不必在MVC版本中重新配置他们的设置。大多数cookie的路径值为/,但其他cookie的路径值为/ scripts。具有/ scripts路径值的那些不包含在Request.Cookies中。
有谁知道如何访问和更新控制器中的/ scripts cookie?顺便说一下,我对MVC还是个新手。
理想情况下,我喜欢服务器端解决方案,但如果不可能,那么客户端解决方案应该是可行的。
由于
答案 0 :(得分:0)
对于那些想知道为什么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();
}
答案 1 :(得分:-1)
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 "";
}