为什么我在反应中获取它时没有得到会话?
Why doesn't i get the session when i fetch it in react?
当我将端点粘贴到浏览器中时 url 并保存并获取会话,它就可以正常工作。
但是当我像这样用 react fetch 尝试它时:
fetch(`https://localhost:44369/api/users/save-to-session?userId=${userId}`, {
method: "GET",
mode: "cors",
credentials: "include",
}).then(() => {
fetch(`https://localhost:44369/api/users/fetch-from-session`, {
method: "GET",
mode: "cors",
credentials: "include",
})
.then(function (body) {
return body.text();
})
.then((response) => {
console.log(response);
});
});
我得到空值。
这是 asp.net 核心网络 api 端点
[HttpGet]
[Route("save-to-session")]
public IActionResult SaveToSession(string userId)
{
HttpContext.Session.SetString("user", userId);
return Content(userId);
}
[HttpGet]
[Route("fetch-from-session")]
public IActionResult FetchFromSession()
{
string name = HttpContext.Session.GetString("user");
return Ok(name);
}
可能是因为 CORS?
这是在我的启动文件中:
services.AddCors();
services.AddMvc();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(60);
options.Cookie.HttpOnly = false;
options.Cookie.IsEssential = true;
});
app.UseCors(options => options.WithOrigins("http://localhost:3000")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
当从 http
客户端向 https
服务器发送带有 cookie 的请求时,您应该将 Security
设置为真
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(60);
options.Cookie.HttpOnly = false;
options.Cookie.IsEssential = true;
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
当我将端点粘贴到浏览器中时 url 并保存并获取会话,它就可以正常工作。
但是当我像这样用 react fetch 尝试它时:
fetch(`https://localhost:44369/api/users/save-to-session?userId=${userId}`, {
method: "GET",
mode: "cors",
credentials: "include",
}).then(() => {
fetch(`https://localhost:44369/api/users/fetch-from-session`, {
method: "GET",
mode: "cors",
credentials: "include",
})
.then(function (body) {
return body.text();
})
.then((response) => {
console.log(response);
});
});
我得到空值。
这是 asp.net 核心网络 api 端点
[HttpGet]
[Route("save-to-session")]
public IActionResult SaveToSession(string userId)
{
HttpContext.Session.SetString("user", userId);
return Content(userId);
}
[HttpGet]
[Route("fetch-from-session")]
public IActionResult FetchFromSession()
{
string name = HttpContext.Session.GetString("user");
return Ok(name);
}
可能是因为 CORS? 这是在我的启动文件中:
services.AddCors();
services.AddMvc();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(60);
options.Cookie.HttpOnly = false;
options.Cookie.IsEssential = true;
});
app.UseCors(options => options.WithOrigins("http://localhost:3000")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
当从 http
客户端向 https
服务器发送带有 cookie 的请求时,您应该将 Security
设置为真
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(60);
options.Cookie.HttpOnly = false;
options.Cookie.IsEssential = true;
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});