[Web API] Sessions

By default, Sessions are not supported in Web API. The one of the design principles of Web API is atomic. But in some cases, you want to access session data. Let’s find out how can you do that.


1. HttpContext

The “System.Web.HttpContext” class provides the session-related properties and methods.

public sealed class HttpContext
  public HttpSessionState Session { get; }
  public void SetSessionStateBehavior(SessionStateBehavior sessionStateBehavior);


2. SessionStateBehavior Enum

public enum SessionStateBehavior
  Default = 0,
  Required = 1,
  ReadOnly = 2,
  Disabled = 3


3. Setting SessionStateBehavior for Web API

The problem is to where and when you need to call the “SetSessionStateBehavior()” method.

In MVC applications, you can use the “Application_PostAuthorizeRequest()” in the “Global.asax“.

protected void Application_PostAuthorizeRequest()
  if (IsWebApiRequest())

private static bool IsWebApiRequest()
  return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(@"~/api");

This code enables the Session for Web API calls.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s