首页 > 解决方案 > 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 调用也可以正常工作,并且不会触发新会话,但是我正在尝试删除对 j​​Query 的依赖。

想法?

标签: javascriptc#jqueryasp.net-mvcfetch-api

解决方案


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'

推荐阅读