会话未保存在 ServiceStack 中 [英] Session not saved in ServiceStack

查看:51
本文介绍了会话未保存在 ServiceStack 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用会话功能但不进行身份验证.我已经将 Plugins.Add(new SessionFeature()) 添加到 AppHost.cs 并且我有以下代码

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

    } 
}
}

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

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

推荐答案

您需要使用 base.SaveSession() 保存会话.请参阅此处靠近底部的部分标题为保存在服务中".

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

更新:

扩展方法存在 Resharper 问题,请参阅此处,其中似乎影响 SaveSession().解决办法:

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

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

这篇关于会话未保存在 ServiceStack 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆