Step 1:- Create SessionHttpControllerHandler class under Global.asax.cs
using System.Web.Http.WebHost;
using System.Web.SessionState;
public class SessionHttpControllerHandler : HttpControllerHandler, IRequiresSessionState
{
public SessionHttpControllerHandler(RouteData routeData)
: base(routeData)
{
}
}
Step 2:- Create SessionHttpControllerRouteHandler class under Global.asax.cs
public class SessionHttpControllerRouteHandler : HttpControllerRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new SessionHttpControllerHandler(requestContext.RouteData);
}
}
Step 3:- Create SessionHttpControllerRouteHandler class under Global.asax.cs
public class SessionHttpControllerRouteHandler : HttpControllerRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new SessionHttpControllerHandler(requestContext.RouteData);
}
}
Step 4:- Open WebApiConfig.cs under App_Start folder and Comment following Code
public static void Register(HttpConfiguration config)
{
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
}
Step 5:- Open RouteConfig.cs under App_Start folder and Copy Past highlighted code
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
).RouteHandler = new SessionHttpControllerRouteHandler();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Question", action = "Index", id = UrlParameter.Optional }
);
}
Step 6:- Api
Controller
public class TestController : ApiController
{
public string Get()
{
var session = System.Web.HttpContext.Current.Session;
if (session != null)
{
// Add Your Code here
}
return "No Session
Exists";
}
}
Note:-
It's not compulsory
to create a class in Global.asax.cs file. You can also add in model.