【问题标题】:nancyfx cookies based session values in Get can't be found in Post and vice versa在 Get 中找不到基于 nancyfx cookie 的会话值,在 Post 中找不到,反之亦然
【发布时间】:2014-06-06 09:24:44
【问题描述】:

我正在尝试使用 Nancyfx 自托管。问题是当我在Get["path"] 中设置Session["key"] = value,然后我在Post["path"] 中调用它时,我得到空,反之亦然。下面是我的代码

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();
    }
}

由于这个问题,现在我无法保存登录状态或一些必要的信息。你们有解决办法吗?

【问题讨论】:

  • Cookie 不会重新附加到您发出的每个请求。按预期工作。

标签: session nancy


【解决方案1】:

@phill 指出您发布的代码按预期工作。

实际上,您的引导程序和模块可以正常工作,并且会话可以从所有处理程序访问。

问题在于,当您创建新的 HttpWebRequest 时,之前调用的 cookie 不会被保留。要将 cookie 从一个此类请求转移到下一个请求,请按照 this answer 的说明进行操作。

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多