javascript - Fetch API 调用导致新的 Asp.net 会话
问题描述
我正在我的一个 asp.net mvc 项目中删除 jQuery,转而使用纯原版 JS。现在我已经$.ajax
用 Fetch API 调用替换了 POST 调用,每个调用都会在服务器上触发一个新会话。
在过去的几天里,这一直让我陷入困境,我已经将其范围缩小到特别是从使用 jQuery Ajax 到 Fetch API 的转换。我的新 Fetch API 调用在其他方面工作得很好,仍然执行所需的服务器端工作。一旦他们返回,就会触发一个新的服务器会话。
显然,这是一个主要问题,因为我的用户会话数据不断被重置。知道为什么会这样吗?或者任何人都知道任何解决方法,而不必恢复使用 jQuery?
我之前的基于 'jQuery' 的 POST 调用:
Post(route, data) {
$.ajax({
type: 'POST',
url: route,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8"
}).done((result, statusText, jqXHR) => {
return result;
});
}
我新的基于“获取 API”的调用:
async Post(route, data) {
let response = await fetch(route, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
},
body: JSON.stringify(data)
});
let result = await response.json();
return result;
}
在我的Global.asax.cs
:
protected void Session_Start(object o, EventArgs e) {
Debug.WriteLine("Session_Start");
HttpContext.Current.Session.Add("__MySessionData", new MySessionDataClass());
}
正如我上面提到的,Fetch API 调用工作得非常好,而不是重置我的会话,我从Debug.WriteLine
调用中知道。jQuery Ajax 调用也可以正常工作,并且不会触发新会话,但是我正在尝试删除对 jQuery 的依赖。
想法?
解决方案
You're not passing in the ASP.NET_SessionId
cookie with your custom request.
You are using fetch
. By default it uses omit
for the credentials
. This means, as said on the MDN page:
By default,
fetch
won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).
JQuery does send cookies, but only those on the same domain.
AJAX calls only send Cookies if the url you're calling is on the same domain as your calling script.
Source
To fix this, you need to tell fetch
to send cookies. From this post:
fetch('/something', { credentials: 'same-origin' }) // or 'include'
推荐阅读
- javascript - 仅合并重复的重复对象
- javascript - Laravel\Blade - 获取动态添加的选定单选按钮的值
- sails.js - (Sails V1 + MongoDB) 如何使用 SailsJS 在 MongoDB 中创建动态集合/表?
- unit-testing - Firebase 函数 TypeScript 单元测试 devDependencies
- java - 在 leetcode 中,为什么 java 的性能优于 scala
- matlab - 使用 imread 和 csvwrite 从图像集中创建 csv 文件时出现 Matlab 错误
- kendo-ui - 将事件绑定到 Kendo 下拉列表时未捕获的类型错误
- java - Spring Service 名称与接口名称冲突
- ruby-on-rails - 如何解决哈希文字中的重复键
- java-ee-7 - 在 Java SE 中嵌入 Payara