I have aplication by .Net Core API 7 and my app will save user info by session like this code when they login
public int _UserId
{
get
{
if (HttpContext.Session.GetInt32("UserId") == null)
{
HttpContext.Session.SetInt32("UserId", 0);
}
return (int)HttpContext.Session.GetInt32("UserId");
}
set
{
HttpContext.Session.SetInt32("UserId", value);
}
}
When the user calls other api, my program will auto get session and work with this. When I use Postman and Swagger Ui it work well.
The problem is when I call api by js, it is not in the same cookie(I really don’t know what to call it ). In this below code, I call login API and this success, my program will save session. Then I call api GetCurrentUser
to get session which I have been saved before and I can’t get result because two functions I call are not in the same cookie
async function callApiLogin(username, password) {
const xhttp = new XMLHttpRequest();
const url = "http://localhost:5296/api/Account/Login";
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onload = function () {
if (xhttp.status === 200) {
const response = xhttp.responseText;
console.log(response);
} else {
// Handle error
}
};
const data = {
username: username,
password: password,
};
xhttp.send(JSON.stringify(data));
}
callApiLogin("string1", "string");
console.log("Login completed");
setTimeout(() => {
const xhttp = new XMLHttpRequest();
const url = "http://localhost:5296/api/User/GetCurrentUser"; // Replace with the actual API endpoint
xhttp.open("GET", url, true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onload = function () {
if (xhttp.status === 200) {
const response = xhttp.responseText;
console.log(response);
} else {
// Handle error
}
};
xhttp.send();
}, 5000);
How can I call API by js in the same cookie like Swagger and Postman?
Should I use JWT token instead of sessions?
2
Answers
In this case, XML Request won’t automatically include cookie. Try something like this:
When making requests from JavaScript, you need to ensure that you include cookies in your requests. You can do this using the fetch API or Axios. Here’s an example using fetch.