Search code examples
sessionnancy

nancyfx cookies based session values in Get can't be found in Post and vice versa


I'm trying with Nancyfx self hosting. The problem is when I set Session["key"] = value in Get["path"], then I call it in Post["path"], I get empty and vice versa. Below is my code

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

public class TestModule : NancyModule
{
    public TestModule()
    {
        Get["/"] = _ =>
        {
            Session["App1"] = "Ola";

            return Session["App1"] + " " + "Hello World";//"Ola Hello World"
        };

        Get["/about"] = _ =>
        {
            return Session["App1"];//"Ola Hello World"
        };

        Post["/create"] = _ =>
        {
            return Session["App1"];//emtpty
        };

        Post["/add"] = _ =>
        {
            return Session["App1"];//empty
        };
    }
}

class Program
{
    static void Main(string[] args)
    {
        var cfg = new HostConfiguration();
        cfg.UrlReservations.CreateAutomatically = true;
        var host = new NancyHost(new Bootstrapper(), cfg, new Uri("http://localhost:5050"));
        host.Start();

        Console.ReadKey();

        WebRequest wr1 = HttpWebRequest.Create("http://localhost:5050/create");

        wr1.Method = "POST";

        wr1.GetRequestStream();

        StreamReader sr1 = new StreamReader(wr1.GetResponse().GetResponseStream());

        Console.WriteLine(sr1.ReadToEnd());

        Console.ReadKey();

        WebRequest wr2 = HttpWebRequest.Create("http://localhost:5050/add");

        wr2.Method = "POST";

        wr2.GetRequestStream();

        StreamReader sr2 = new StreamReader(wr2.GetResponse().GetResponseStream());

        Console.WriteLine(sr2.ReadToEnd());

        Console.ReadKey();

        host.Stop();
    }
}

With this problem, now I have no way to save login status or some necessary info. Do you guys have a solution?


Solution

  • As @phill points out the code you posted works as expected.

    In fact your bootstrapper and module works, and the session is accessible from all the handlers.

    The problem is that when you create new HttpWebRequests the cookies from earlier calls are not preserved. To carry over the cookies from one such request to the next do what this answer says.