Reputation: 61
I am developing an ASP.NET Web API application where I need to manage session state based on a session ID sent from an Angular application. The session ID should be created if it does not exist, and if it already exists, it should return the existing session value.
The problem I am encountering is that when I send a session ID for the first time, it correctly creates the session. However, when I send a second request with the same session ID, it does not find the existing session and creates a new one instead.
this is the code: Controller:
[HttpGet]
[Route("GetAll/{sessionId}")]
// GET: api/Bookmark
public IHttpActionResult Get(string sessionId)
{
try
{
var session = GetSession(sessionId);
var repos = _getRepositoriesFromSession(session);
return Ok(repos);
}catch(Exception ex)
{
return BadRequest(ex.Message);
}
}
private List<GithubRepositoryDTO> _getRepositoriesFromSession(HttpSessionState session)
{
var repos = session["Repositories"] as List<GithubRepositoryDTO>;
if (repos == null)
{
repos = new List<GithubRepositoryDTO>();
session["Repositories"] = repos;
}
return repos;
}
How session generated and handled:
protected HttpSessionState GetSession(string sessionId)
{
var context = HttpContext.Current;
// Ensure the session ID is correctly set in the context
if (context.Session == null || context.Session.SessionID != sessionId)
{
var sessionContainer = new HttpSessionStateContainer(
sessionId,
new SessionStateItemCollection(),
new HttpStaticObjectsCollection(),
10,
true,
HttpCookieMode.UseUri,
SessionStateMode.InProc,
false
);
SessionStateUtility.AddHttpSessionStateToContext(context, sessionContainer);
}
return context.Session;
}
Web.config:
<system.web>
<compilation debug="true" targetFramework="4.8" />
<httpRuntime targetFramework="4.8" />
<sessionState mode="InProc" cookieless="true" timeout="20" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
Upvotes: 0
Views: 26