When i paste the endpoint int the browser url and save and fetch the session it works.
But when i try it with react fetch like this:
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);
});
});
I get null back.
This is the asp.net core web api endpoint
[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);
}
It could be because of CORS? This is in my startup file:
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());
You should set Security
as true when send request with cookie from a http
client to a https
server
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;
});