Disabling session for Web API controllers

If you've implemented Web API controllers in Sitecore 8.1 (and therefore MVC 5.2) you may have noticed that requests to these controllers create and/or maintain an associated ASP.NET session on your server. But there may be situations where session isn't required for this controller (such as a very "stateless" REST API endpoint), so how can you remove session and save your server a bit of work?ASP.NET Web API logo

Sitecore Support helped me find the answer to this; If you dig down from the Sitecore.Mvc.Pipelines.Loader.InitializeRoutes pipeline processor, you'll see all route handlers getting wrapped by Sitecore.Mvc.Routing.RouteHttpHandler, which eventually ensures that session is spun up when that route is used.

However, if you register your API routes in a pipeline processor which runs *after* Sitecore.Mvc.Pipelines.Loader.InitializeRoutes, this doesn't happen. See a bit more detail on registering custom MVC routes in Sitecore here.

As a quick example, here's a Web API controller which attempts to use session:

using System;
using System.Globalization;
using System.Web;
using System.Web.Http;

namespace WebApiTest.Controllers
    public class TestController : ApiController
        public IHttpActionResult Hello()
            var lastDateTime = HttpContext.Current.Session["lastDateTime"] ?? "N/A";
            HttpContext.Current.Session["lastDateTime"] = DateTime.Now.ToString(CultureInfo.InvariantCulture);

            return Ok("previous request was at " + lastDateTime);

Let's also​ create a pipeline processor class which registers a route for API calls:

using System.Web.Http;
using System.Web.Routing;
using Sitecore.Pipelines;

namespace WebApiTest
    public class ScRouteConfig
        public void Process(PipelineArgs args)
            RouteTable.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}");

Finally let's patch this pipeline processor in - be careful that your patch file is executed after all the other Sitecore "include" files (always check this using showconfig.aspx...):

<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" >
        <processor type="WebApiTest.ScRouteConfig, WebApiTest"
          patch:after="processor[@type='Sitecore.Mvc.Pipelines.Loader.InitializeRoutes, Sitecore.Mvc']" />

You should now be able to visit http://sitecore81160302.local/api/test/hello ​and see the Web API response *error* because HttpContext.Current.Session​ is null - this shows there is now no session!

By James at 16 Dec 2017, 16:12 PM


Post a comment