.NET CORE 使用存放在数据库的Session

https://blog.csdn.net/u012601647/article/details/68553611

session既可以放在内存中,也可以储存在数据库中,.net core提供了储存在数据库中的配置
首先,需要通过cmd指令生成session数据库,生成数据库字段为Id,Value,ExpiresAtTime,

SlidingExpirationInSeconds,AbsoluteExpiration

其次,进行session配置:

(1)startup.cs文件中,找到ConfigureServices(IServiceCollection services)方法注入Session,
     //sessionDB
    services.AddDistributedSqlServerCache(o =>
      {
       o.ConnectionString = "server=10.1.1.10;database=aaaaa;uid=sa;pwd=P@ssw0rd;";
       o.SchemaName = "dbo";
       o.TableName = "SessionState";
       });
    //sessionb timeout
       services.AddSession(o =>
       {
        o.IdleTimeout = TimeSpan.FromSeconds(1800);
       });
(2)找到Configure方法,注入session
    //sessionDB
    app.UseSession();
之后我们就可以在controller中使用session了。
HttpContext.Session.SetString("code","123456");
HttpContext.Session.GetString("code");
注意:注入时会提示某些包需要引入,code可以通过工具将nut包下载到工程中。
Microsoft.AspNetCore.Session。
但是core的session仅限于controller,想在其他地方使用,还需要进行IHttpContextAccessor注解。
首先在startup.cs文件中ConfigureServices(IServiceCollection services)方法进行HttpContextAccessor注解。
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

其次找到Configure方法,添加IServiceProvider svp参数,在方法中添加【MyHttpContext.ServiceProvider = svp;】

进行注入之后在自定义MyHttpContext类

public static class MyHttpContext
{
  public static IServiceProvider ServiceProvider;
    static MyHttpContext()
    { }
    public static HttpContext Current
    {
      get
       {
         object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));
         HttpContext context = ((IHttpContextAccessor)factory).HttpContext;
          return context;
       }
  }
}
注意:添加类如果在FrameWork类库中,需要引入
Microsoft.AspNetCore.Html.Abstractions.DLL
Microsoft.AspNetCore.Http.DLL 
Microsoft.AspNetCore.Http.Abstractions.DLL

使用时MyHttpContext.Current.Session.SetString("code","123456");
MyHttpContext.Current.Session.GetString("code");

注意:在其他类库中使用时如果报错,还需要引入
Microsoft.AspNetCore.Http.DLL
Microsoft.AspNetCore.Http.Abstractions.DLL
Microsoft.AspNetCore.Http.Extensions.DLL
Microsoft.AspNetCore.Http.Features.DLL
Microsoft.AspNetCore.HttpOverrides.DLL

友情提示:seivice类的注入: services.AddTransient<ISiteContract, SiteService>();
--------------------- 
作者:菜鸟小灰灰 
来源:CSDN 
原文:https://blog.csdn.net/u012601647/article/details/68553611?utm_source=copy 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/hezhixiang/article/details/83038520