0

This is my session save and fetch method:

    [HttpPost]
    [Route("save-to-session")]
    public IActionResult SaveToSession(string id)
    {
        HttpContext.Session.SetString("user", id);
        return Content(id);
    }

    [HttpGet]
    [Route("fetch-from-session")]
    public IActionResult FetchFromSession()
    {
        string name = HttpContext.Session.GetString("user");
        return Content(name);
    }

I'm using Sql Server Cache:

 services.AddDistributedSqlServerCache(options => {
            options.ConnectionString = Configuration.GetConnectionString("TestMEApiContext");
            options.SchemaName = "dbo";
            options.TableName = "Session";
        });

        services.AddSession(options => {
            options.Cookie.Name = ".Session";
            options.IdleTimeout = TimeSpan.FromMinutes(3000);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });

and the data is saved to the database but when i try to fetch it always returns null.

This is how i try to fetch it in my react code:

 fetch(`https://localhost:44369/api/users/fetch-from-session`, { method: 'GET', credentials: 'include', mode: 'cors' }).then(function (body) {
        return body.text();
    }).then((response) => {
        console.log("My response")
        console.log(response) // <-THIS IS NULL
    });

And this is how i try to save it but save works:

 await this.getUserId().then(async function (userId) {
                    fetch(`https://localhost:44369/api/users/save-to-session?id=${userId}`, {
                        method: 'POST',
                        mode: 'cors',
                        credentials: 'include'
                    });
                })
  • Did you add `app.UseSession()` in `Configure()` method in your `Startup`? More details can be found in [official docs](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-5.0). – Prolog Mar 20 '21 at 11:59
  • Yes, i have already added `app.UseSession();` – Levente Makszimus Mar 20 '21 at 12:02
  • I suggest debugging by striping down what you've got and commenting out what you can. Aim for minimal working infrastructure to test. Step by step bring back the custom parts you have to the point where you are now. I've used your code to create a minimum web app with cache and local SQL db and it works so, there must be something between your code and the minimum web app that breaks the mechanism. If the data is saved in the database, that means you've correctly configured saving the cache, the problem is in retrieving it. Check endpoints bare response. – Prolog Mar 20 '21 at 12:28

0 Answers0