user4310768
user4310768

Reputation:

Session lost in .Net core when making fetch request from JS

When making request from JS to controller sessionvalue that is previously set gets lost. How do I prevent that? Below var instanceId returns null.

    [AllowAnonymous]
    public JsonResult GetEmails()
    {
        var instanceId = HttpContext.Session.GetString("instanceId");
        HttpContext.Items.Add("instanceId", instanceId);
        var result = someapicall;
        var returnObj = JsonConvert.SerializeObject(result);
        return Json(returnObj);
    }

The JS is just a standard fetch to said controller action.

Upvotes: 0

Views: 1064

Answers (1)

Henk Mollema
Henk Mollema

Reputation: 46581

Does your JavaScript fetch-request sends the ASP.NET Core cookies along with it? The session state uses a cookie to track and identify requests and load the correct data. If a request doesn't sends the cookie it won't be able to figure out which session the request is tied to.

Please refer to the documentation for more info about session state in ASP.NET Core.

Edit
For completeness: the solution is to add credentials: true for fetch-requests so it will send cookies along with the request. For example:

{ method: 'GET', credentials: 'include' }

For AJAX requests you should add the withCredentials property, which has the same purpose:

$.ajax({
   url: '/some/url',
   // ...
   xhrFields: {
      withCredentials: true
   }
});

Or set it globally, for all requests:

$.ajaxSetup({
    // ...
    xhrFields: {
       withCredentials: true
    }
});

Upvotes: 3

Related Questions