Rob Jefferies Rob Jefferies - 1 month ago 25
ASP.NET (C#) Question

Unable to access ASP.NET session object in Nancy Module

I'm trying to combine an MVC3 application with some Nancy modules. In my application I'm trying to set a session variable in the MVC3 controller and then read that variable in the Nancy module. When I attempt to read the variable in the Nancy controller the Session object is null.

Here is a gist of my MVC3 controller, Nancy module, and root web.config.

https://gist.github.com/3105219

It looks like all(most) of the other objects hanging off the Current httpcontext is not null and looks "normal" when comparing it in the MVC3 section of the application.

Edit: Further testing shows that I can't access the ASP.NET session in a raw Nancy application. I created the application using the steps at the bottom of this page in section "Creating your first Nancy application".

https://github.com/NancyFx/Nancy/wiki/Introduction

Here is the web.config of the simple Nancy application.

https://gist.github.com/3105583

Answer

You have to create a BootStrapper to provide session services in Nancy. Session services are provided by ISession interface. Nancy comes with couple of default implementations: NullSessionProvider and Session. I guess the default one is NullSessionProvider. The other implementation stores the data in process and doesn't uses cookies. To create a cookie based sessions you have to create a bootstrapper as below.

public class Bootstrapper : DefaultNancyBootstrapper
{
    protected override void ApplicationStartup(TinyIoCContainer container, IPipelines  pipelines)
    {
      CookieBasedSessions.Enable(pipelines);
    }
}

Ref. http://blog.csainty.com/

EDIT:

From my understanding Nancy uses it's own context classes to provide request, session, cache and other stuff. It's the bootstrappers that helps to provide these services. I'm not sure you can use ASP.NET objects like HttpContext, HttpSession straightly as default in Nancy.