Context Values in Generic Handlers (.ASHX) and Web Services / WebMethods (.ASMX)
By default in .NET framework, Generic Handlers and Web Services are processed in session separate from the one created upon visiting site using the usual means (.ASPX). This article explains what it means for you as a Kentico developer and how to modify your code in order to use the main session.
.NET Generic Handlers are not to be confused with Kentico Global Event Handlers.
By default in .NET framework, Generic Handlers and Web Services are processed in session separate from the one created upon visiting site using the usual means (.ASPX). Separate contexts, including completely separate context values, are generated when you try to access a Handler or Web Service. This may not be an issue when trying to modify a database object using API, but can cause problems when trying to modify objects stored both in database and visitor’s context variables.
An example of this is modifying the contents of a user’s shopping cart, when you are adding or manipulating existing shopping cart items. Any such changes will correctly save to the database, but since the Generic Handler or Web Service uses its own session, it will not immediately propagate changes to the customer visiting your website, even after refreshing it.
In order to make sure your Generic Handler uses main session instead of creating its own, it has to implement either IReadOnlySessionState or IRequiresSessionState interface. The second option is required if you implement your project on Microsoft Azure platform. Both of these can be found in System.Web.SessionState library.
A similar method is used for the Web Service. The only modification code modification you need to make is to set variable “EnableSession = true” in the WebMethod attribute: [WebMethod(EnableSession = true)]. In addition to that, the Web Service needs to be run from the same application pool and on the same domain as the main site in order to be able to share its session.
Applies to: Kentico CMS 7.0