WebAPI: Accessing Session Using ASP.NET Web API

Standard

I know its not the way WebAPI should be used, Lot of people gonna offend on this, but it happens sometime that you need to use session objects in you api calls. I know I know it defeats the purpose of stateless factor of restful api, but sometimes due to nature of requirements and existed architecture(poor but have to deal with it)

We can consume session object in web api methods by using below code:

protected void Application_Start()
{
    Init();
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    AuthConfig.RegisterAuth();
}

public override void Init()
{
    this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
    base.Init();
}

void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s