2013-03-14 53 views
1

我想使用會話功能但沒有進行身份驗證。 我已經加入到Plugins.Add(new SessionFeature())AppHost.cs我有以下代碼未保存在ServiceStack中的會話

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

您將需要使用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-空格重新格式化
  • RequestContext.Get<IHttpRequest>().SaveSession(CustomSession)可以保存 會話。
+0

我試過,但我得到這個錯誤:ServiceStack.ServiceInterface.Service'不包含'SaveSession'的定義謝謝 – user2170206 2013-03-14 17:15:12

+0

您使用ReSharper嗎?我用一些解決方法更新了我的答案。 – paaschpa 2013-03-14 17:32:03

+0

是的,我使用ReSharper,你的工作似乎部分工作,但是當我運行代碼時,調用SaveSession時出現錯誤,它說:{「值不能爲null。\ r \ nParameter name:source」}。另外,對於「sess」,我不能使用自定義類型或字符串,而是使用AuthUserSession。 – user2170206 2013-03-14 18:32:05