Skip to content Skip to sidebar Skip to footer

Fetch Api Call Causes New Asp.net Session

I'm in the process of removing jQuery in one of my asp.net mvc projects in favor of using straight vanilla JS. Now that I've replaced $.ajax POST calls with Fetch API calls, each c

Solution 1:

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, fetchwon'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'

Solution 2:

Figured out the issue with the help of @gunr2171, so self-answering in case anyone else comes across a similar issue.

Turns out that my new Fetch API call was not sending the current Asp.net session cookie with the request, so the server would start a new session thinking that one didn't exist yet. Tweaking the Fetch API call to include credentials: 'include' in the options allows it to send the current session cookie and the server will no longer create a new one after every call.

For reference, my new Fetch API call now looks like:

asyncPost(route, data) {
    let response = await fetch(route, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-type': 'application/json'
        },
        credentials: 'include',
        body: JSON.stringify(data)
    });
    let result = await response.json();
    return result;
}

Post a Comment for "Fetch Api Call Causes New Asp.net Session"