会话未保存在ServiceStack中

时间:2013-03-14 14:41:30

标签: session servicestack

我想使用会话功能但没有身份验证。 我已将Plugins.Add(new SessionFeature())添加到AppHost.cs,我有以下代码

public class CustomService : Service
{
public CustomResponse Any(CustomRequest pRequest)
{
    var CustomSession = base.Session.Get<CustomType>("MySession");//try to get the session
    if (CustomSession == null)
    {
        //create a new session
        CustomSession = new CustomType{MyId=1};
        base.Session["MySession"] = CustomSession;
        //base.Session.Set("MySession", CustomSession); //also tried this, to save the session.
        this.SaveSession(CustomSession,  new TimeSpan (0,20,0)); //Save the Session

    } 
}
}

我遇到的问题是base.Session.Get<CustomType>("MySession")总是null。 我是否遗漏了会话实施的内容?

1 个答案:

答案 0 :(得分:1)

您需要使用base.SaveSession()保存会话。请参阅底部附近的here,标题为“正在保存服务”。

public class MyAppHost : AppHostBase
{
    public MyAppHost() : base("MyService", typeof(CustomService).Assembly)
    {
    }

    public override void Configure(Container container)
    {
       Plugins.Add(new SessionFeature()); 
    }
}


public class CustomType : AuthUserSession
{
    public int MyId { get; set; }
}

[Route("/CustomPath")]
public class CustomRequest
{
}

public class CustomResponse
{
}

public class CustomService : Service
{
    public CustomResponse Any(CustomRequest pRequest)
    {
        var CustomSession = base.SessionAs<CustomType>();
        if (CustomSession.MyId == 0)
        {
            CustomSession.MyId = 1; 
            this.SaveSession(CustomSession, new TimeSpan(0,20,0));
        }

        return new CustomResponse();
    }
}

<强>更新

扩展方法存在Resharper问题,请参阅here,这似乎会影响SaveSession()。 解决方法:

  • ServiceExtensions.SaveSession(this, CustomSession); ReSharper可能会提示重新格式化,它会起作用。
  • Ctrl-Alt-space重新格式化
  • RequestContext.Get<IHttpRequest>().SaveSession(CustomSession)可以保存 会话。