You are in the “Web API with AJAX” article series. This series explains many topics directly or indirectly related to the Web API. You can visit our old articles here:
I hope that by seeing the title you have clicked on a link and your intention is to go through it very quickly or you may think, why a session management article? This series exlains the Web API in the perspective of AJAX. Yes you are correct; there is no direct relation between session management and AJAX. Intentionally I have put it here by believing the fact:
“Learning is learning, no matter from where it is”.
Ok, so now to start with our actual topic, session management in the Web API. We all know that the Web API is one kind of RESTful service built on top of the HTTP protocol. And by nature HTTP is stateless, in other words for a web server each and every request is a new request. But people are clever with the HTTP protocol (Ha..Ha..) they have introduced a trick to make the HTTP protocol a stateful protocol. The trick is nothing but a Session.
Now, we have all used a session in a normal WebForm application. And we have a basic concept of it but you may not have implemented a session in the Web API.
By default the session handling option is not enabled in the Web API. We need to configure it in the Global.asax page.
Use the following procedure to configure the entire application.
Step 1: Add the properties
Add the following two properties in the Global.asax page.
private const string _WebApiPrefix = "api";
private static string _WebApiExecutionPath = String.Format("~/{0}", _WebApiPrefix);
Step 2: Add the functions
Add both of the following functions within the “Application” class of the Global.asax page.
protected void Application_PostAuthorizeRequest()
{
if (IsWebApiRequest())
{
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
}
private static bool IsWebApiRequest()
{
return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(_WebApiExecutionPath);
}
So here we are done with our Global.asax configuration. The following is the full implementation of the Global.asax page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.WebHost;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.SessionState;
namespace TestWEB_API
{
public class WebApiApplication : System.Web.HttpApplication
{
private const string _WebApiPrefix = "api";
private static string _WebApiExecutionPath = String.Format("~/{0}", _WebApiPrefix);
protected void Application_PostAuthorizeRequest()
{
if (IsWebApiRequest())
{
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
}
private static bool IsWebApiRequest()
{
return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(_WebApiExecutionPath);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
Note that we have registered Routes in Application_Start() event.
Step 3: Implement client application to consume API
In this example we will implement a ajax() function to call the Web API that we will create in the next step. Have a look at the following example:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestWEB_API.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: 'http://localhost:11129/api/values',
type: 'GET',
dataType: 'json',
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
console.log('a' + textStatus);
}
});
});
</script>
</head>
<body>
</body>
</html>
The API is so simple that it’s not necessary to explain it. Now we will move on to implement the API controller.
Step 4: Implement Web API
This API implementation is an important part of this example. Within the controller we will use a session variable. Try to understand the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using TestWEB_API.Models;
using System.Web.SessionState;
using System.Web.Mvc;
namespace TestWEB_API.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public string Get()
{
var session = HttpContext.Current.Session;
if (session != null)
{
if (session["Time"] == null)
session["Time"] = DateTime.Now;
return "Session Time: " + session["Time"];
}
return "Session is not working";
}
}
}
Since this is a service-based application, we cannot allow it to use a session like a WebForm Application. If we want to use a session then we need to use the Httpcontext class as we implemented within the controller.
This is the output that we are getting in the client end through the session variable.
Conclusion
In this article we have learned to implement a session in a Web API application. I hope it will help you to maintain a session in your Web API application. Thanks for reading this article.