Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Asp.net核心应用程序中的会话丢失_C#_Asp.net_Session_Asp.net Core - Fatal编程技术网

C# Asp.net核心应用程序中的会话丢失

C# Asp.net核心应用程序中的会话丢失,c#,asp.net,session,asp.net-core,C#,Asp.net,Session,Asp.net Core,我在应用程序中使用AddDistributedMemoryCache进行会话,并且 继续丢失IIS中的会话。程序会话在VisualStudio中运行良好 调试模式 这是启动代码: public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddSingleton<IActionContextAccessor, ActionContextAc

我在应用程序中使用AddDistributedMemoryCache进行会话,并且

继续丢失IIS中的会话。程序会话在VisualStudio中运行良好

调试模式

这是启动代码:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
    services.AddOptions();
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

    services.AddMvc();
    services.AddDistributedMemoryCache();
    services.AddSession(opts =>
    {
        opts.IdleTimeout = TimeSpan.FromMinutes(45);
    });
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    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.UseHttpMethodOverride();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}"
            );
        routes.MapRoute(
            name: "AdvertisementImages",
            template: "{controller=MainImage}/{action=Images}/{type}/{name}", // URL with parameters
            defaults: new {type = 0, name = ""} // Parameter defaults
        );
    });
}
public void配置服务(IServiceCollection服务)
{
//添加框架服务。
services.AddSingleton();
services.AddOptions();
services.Configure(Configuration.GetSection(“AppSettings”);
services.AddMvc();
AddDistributedMemoryCache();
services.AddSession(opts=>
{
opts.IdleTimeout=TimeSpan.frommins(45);
});
}
公共void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
{
loggerFactory.AddConsole(Configuration.GetSection(“Logging”);
loggerFactory.AddDebug();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseStaticFiles();
app.UseSession();
app.UseHttpMethodOverride();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”
);
routes.MapRoute(
名称:“广告图片”,
模板:“{controller=MainImage}/{action=Images}/{type}/{name}”,//URL和参数
默认值:新建{type=0,name=”“}//参数默认值
);
});
}
这就是我如何填充会话和检索值:

var newLogin = HttpContext.Session.GetObjectFromJson<TryToLoginModel>("TryToLogin");
var newLogin=HttpContext.Session.GetObjectFromJson(“TryToLogin”);
和GetObjectFromJson的扩展:

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);
    }
}
公共静态类SessionExtensions
{
公共静态void SetObjectAsJson(此ISession会话、字符串键、对象值)
{
SetString(key,JsonConvert.SerializeObject(value));
}
公共静态T GetObjectFromJson(此ISession会话,字符串键)
{
var值=session.GetString(键);
返回值==null?默认值(T):JsonConvert.DeserializeObject(值);
}
}

对HttpContext.Session.GetObjectFromJson进行少量调用后,它返回null。此问题仅在IIS中发生,而不是在visual studio中发生。

您可能还需要配置数据保护(),否则会话可能会受到应用程序重新启动时丢失的内存中密钥的保护。这不会在Visual Studio中本地发生,因为密钥存储在您的用户配置文件中。如果服务器重新启动,会话本身也会进入内存,除非他使用redis之类的东西。我在iframe中渲染,所以我必须添加options.Cookie.SameSite=SameSiteMode.None;到services.AddSession