Craig Craig - 2 months ago 16
C# Question

Web API has no session - need to check if user is authenticated

I'm creating my first WebAPI project, and have hit my first snag. It seems that because the WebAPI model is stateless, I have no Session available to me. So, my attempt to add a session variable when logging in, has failed.

public static void CreateSession(int userId, string firstName, string surname, int timezoneOffset, string timezoneName)
// Create the object.
var session = new SessionToken
FirstName = firstName,
Surname = surname,
TimezoneName = timezoneName,
TimezoneOffset = timezoneOffset,
UserID = userId

// Is there an existing session?
var existing = HttpContext.Current.Session[SESSIONNAME];

// If so, we need to kill it and refresh it. Not sure why we would have this case though.
if (existing != null)

// Create the session.
HttpContext.Current.Session.Add(SESSIONNAME, session);


Session is null, and this is because of the stateless model used by WebAPI.

How can I achieve this with Web API? How can I have something to check and query to see if the current user is valid? My session would normally hold some items such as the chaps name, to render on the layout screen - but it looks like that isn't possible right now.


The recommended approach is using stateless authentication and authorization with tokens.

Since some years, it's very easy to configure your WebAPI to integrate OAuth2 workflow using an OWIN middleware.

Learn how following this tutorial.

What you call session items, in OAuth2 you talk about claims.