2017-04-04 207 views
1

我試着在保存HttpContext.Session到數據庫memmoryAddDistributedSqlServerCache不保存會話到數據庫

問題,而不是服務器只不過是被保存在表和會話總是得到空。

這是我開始了代碼:

public void ConfigureServices(IServiceCollection services) 
    { 
     services.AddMvc(); 
     services.AddDistributedSqlServerCache(options => 
     { 
      options.ConnectionString = @"Data Source=localhost;Initial Catalog=mydb;Integrated Security=True;"; 
      options.SchemaName = "dbo"; 
      options.TableName = "SQLSessions"; 
     }); 

     services.AddSession(options => { 
      options.CookieName = "Test.Session"; 
      options.IdleTimeout = TimeSpan.FromMinutes(60); 
     }); 

    } 


    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IDistributedCache cache) 
    { 
     loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
     loggerFactory.AddDebug(); 

     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
      app.UseDatabaseErrorPage(); 
      app.UseBrowserLink(); 
     } 
     else 
     { 
      app.UseExceptionHandler("/Home/Error"); 
     } 

     app.UseStaticFiles(); 

     app.UseSession(); 

     app.UseForwardedHeaders(new ForwardedHeadersOptions 
     { 
      ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto 
     }); 
     app.UseHttpMethodOverride(); 
     app.UseMvc(routes => 
     { 
      routes.MapRoute(
       name: "default", 
       template: "{controller=Home}/{action=Index}/{id?}" 
       ); 
      routes.MapRoute(
       name: "AdvertisementImages", 
       template: "{controller=Home}/{action=Images}/{type}/{name}", // URL with parameters 
       defaults: new {type = 0, name = ""} // Parameter defaults 
      ); 
     }); 

    } 

,並保存會話我的控制器代碼:

HttpContext.Session.SetObjectAsJson("TryToLogin", newLogin); 

和我的會話擴展:

public static class SessionExtensions 
    { 
     public static void SetObjectAsJson(this ISession session, string key, object value) 
     { 
      session.SetString(key, JsonConvert.SerializeObject(value)); 
     } 

     public static T GetObjectFromJson<T>(this ISession session, string key) 
     { 
      var value = session.GetString(key); 

      return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value); 
     } 
    } 

,這我的會話表架構:

enter image description here

回答