WPF: SessionID management with CookieContainer

.NET, ASP.NET 2.0, Technical stuff, WPF
See comments
Following this post, I succeeded in adding cookie management to my latest WPF prototype. Cookie management in WPF and in WinForms applications is needed when you use a stateful web service, which uses HttpSessionState to store data about the current Session. When a web method is marked with the EnableSession parameter, the web service's Session property is set (otherwise it is null).
However, the client must provide a way to store the cookie in which the SessionID (a unique string identifying the current session) is stored. This is the mechanism that the server uses to identify each client uniquely. The cookies collection is sent with every request, and the corresponding Session object is retrieved accordingly.
In web browsers, when you use JavaScript and XmlHttpRequest to connect to web services (or any other framework like ASP.NET AJAX, etc...), you don't need to bother about that, because cookie management is handled by the browser automatically. In other clients, however, you might need to enable it yourself.
In .NET (Windows Presentation Foundation, Windows Forms), this is very easy: Simply set the CookieContainer property to a new instance.
This instance must be persisted somehow. One simple way to do that is to declare the web service as an attribute of the Win Forms or of the WPF Page. Since the Form or the Page are not recycled, the Cookies stored in the CookieContainer.
Note: Contrarily to what I read, it is not necessary to save the CookieContainer itself as an attribute. If the service is stored as an attribute, then you must only initialize the CookieContainer once, for example in the WPF Page's constructor.
Here is an example for a WPF application:
public partial class Page1 : Page
{
  private GetSessionIdService.Service1 m_oService = new GetSessionIdService.Service1();
  public Page1()
  {
    InitializeComponent();
    m_oService.CookieContainer = new System.Net.CookieContainer();
  }
}
Initializing the CookieContainer property
I updated the WPF prototype accordingly, with an option allowing to enable/disable the use of the CookieContainer.
The importance of Global.asax
Note that the Global.asax must be added to the web service in order to allow Session management on the web server. See this post for more information.
Previous entry | Next blog entry

Comments for WPF: SessionID management with CookieContainer