Session not saved in ServiceStack

半城伤御伤魂 提交于 2019-12-24 11:27:53

问题


I want to use the session feature but without athentication. I already added Plugins.Add(new SessionFeature()) to AppHost.cs and I have the following code

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

    } 
}
}

The problem I'm having is that base.Session.Get<CustomType>("MySession") is always null. Am I missing something on the implementation of sessions?


回答1:


You will need to save your session using base.SaveSession(). See here near the bottom there is a section title 'Saving in Service'.

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

Update:

There is a Resharper issue with extension methods, see here, which seems to affect SaveSession(). Work Arounds:

  • ServiceExtensions.SaveSession(this, CustomSession); ReSharper may prompt to reformat and it will work.
  • Ctrl-Alt-space to reformat
  • RequestContext.Get<IHttpRequest>().SaveSession(CustomSession) can save the session.


来源:https://stackoverflow.com/questions/15412350/session-not-saved-in-servicestack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!