为什么 cookie 不存储在 ASP.NET Core Web API 的浏览器中?
Why cookie does not store in browser in ASP.NET Core Web API?
我在 ASP.NET Core Web API 中使用 cookie 身份验证。当我向 Postman 请求登录时,Cookie 显示在 Postman 中。
但是当我从 ajax 请求它时,cookie 没有存储在浏览器中。
这是我的 Ajax 请求 - 我是否遗漏了 Ajax 中的任何内容?
$.ajax({
url: 'http://localhost:61610/api/auth/login',
method: 'POST',
xhrFields: {
'Access-Control-Allow-Credentials': true
},
data: JSON.stringify(para),
dataType: 'application/json',
contentType: 'application/json; charset=utf-8',
success: function (result, status, jqXHR) {
console.log(result);
alert(status);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
你应该试试这个
xhrFields: {
withCredentials: true
}
您需要对 ajax 进行一些更改:
$.ajax({
url: 'http://localhost:61610/api/auth/login',
method: 'POST',
xhrFields: {
withCredentials: true
},
data: JSON.stringify(a),
dataType: 'application/json',
contentType: 'application/json; charset=utf-8',
success: function (result, status, jqXHR) {
console.log(result);
alert(status);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
然后你可以用 cookie 发送 ajax
这里有一个link有更详细的解释:
我在 ASP.NET Core Web API 中使用 cookie 身份验证。当我向 Postman 请求登录时,Cookie 显示在 Postman 中。
但是当我从 ajax 请求它时,cookie 没有存储在浏览器中。
这是我的 Ajax 请求 - 我是否遗漏了 Ajax 中的任何内容?
$.ajax({
url: 'http://localhost:61610/api/auth/login',
method: 'POST',
xhrFields: {
'Access-Control-Allow-Credentials': true
},
data: JSON.stringify(para),
dataType: 'application/json',
contentType: 'application/json; charset=utf-8',
success: function (result, status, jqXHR) {
console.log(result);
alert(status);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
你应该试试这个
xhrFields: {
withCredentials: true
}
您需要对 ajax 进行一些更改:
$.ajax({
url: 'http://localhost:61610/api/auth/login',
method: 'POST',
xhrFields: {
withCredentials: true
},
data: JSON.stringify(a),
dataType: 'application/json',
contentType: 'application/json; charset=utf-8',
success: function (result, status, jqXHR) {
console.log(result);
alert(status);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
然后你可以用 cookie 发送 ajax
这里有一个link有更详细的解释: