将会话超时增加到一周或更长时间

Increasing session timeout to a week or more

为了增加会话超时,看来我会使用以下设置:

<system.web>
  <sessionState mode="InProc" timeout="20" />
  /* Etc... */
</system.web>

此处超时设置为20分钟(默认值)。而且,显然,最大值是 525,600 分钟,或一年。

我可以在一周后返回 Facebook,并且我仍然处于登录状态。这就是我希望我的应用程序的行为方式。但根据 this answer,这会对性能产生不利影响,因为 "your inactive sessions will remain in Web server memory which may cause application pool to recycle, which would result in loosing all sessions for all users."

有人知道有关此性能影响的详细信息吗?而且,如果这是真的,是否有更高效的方式让用户保持登录状态,例如 Facebook 等网站?

更新:

下面是我当前 web.config 文件的相关部分。

<system.web>
  <authentication mode="None" />
  <sessionState mode="InProc" timeout="60" />
  <compilation debug="true" targetFramework="4.6" />
  <httpRuntime targetFramework="4.5.2" executionTimeout="240" maxRequestLength="20480" />
  <httpModules>
    <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
  </httpModules>
  <customErrors mode="Off"></customErrors>
</system.web>
<system.webServer>
  <modules>
    <remove name="FormsAuthentication" />
    <remove name="ApplicationInsightsWebTracking" />
    <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
  </modules>
  <validation validateIntegratedModeConfiguration="false" />
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="20971520" />
    </requestFiltering>
  </security>
</system.webServer>

更新 2:

看来我错误地将两个问题(身份验证和会话状态)混为一谈。对于我在谷歌上搜索的一些问题没有正确分类,我深表歉意。我的目标只是延长用户登录的时间长度。

对于登录,您必须使用 FormsAuthenticationASP.NET Identity(基于 cookie 的身份验证的改进版本 FormsAuthentication),这允许您将身份验证 cookie 保留超过 weeks/months. FormsAuthentication是无状态的,为了支持多服务器,可以在所有服务器中使用单个machineKey。默认情况下,所有示例和教程大多指导使用 FormsAuthentication

Facebook 和所有人都使用身份验证 cookie,没有人使用 Session 进行登录。

理想情况下 Session 是不好的,而且几乎没有必要。可以用HttpRuntime.Cache代替。可以轻松设置缓存以使用某些外部提供程序,例如 Fabric 缓存或 Redis。要使缓存被用户隔离,您可以简单地在缓存项的键上附加用户名。

更新

使用 FormsAuthentication 没有任何缺点,只是解密 cookie 所需的开销很少 CPU,但也可以通过缓存身份验证票证来避免。

支持 Session 的唯一原因可能是与他们可能支持的旧 ASP 应用程序兼容。

在新的 ASP.NET MVC 示例中,他们在代码中配置了基于 cookie 的身份验证(在启动时),这不是会话。虽然在web.config中配置了session,但只要你不想在session中存储任何东西,你可以完全禁用它。

您引用的答案部分正确。这取决于会话状态的存储位置。

在 SQL 服务器数据库中存储会话状态时增加会话状态应该没有问题。还使用 Web Farms - 这对于满足可伸缩性很有意义。

来自这篇文章:

Storing Session State in a SQL Server Database

Storing session variables in the SQL server has the following advantages:

Scalability: If you are looking for a highly scalable option to store your session variables, the SQL Server option is for you. It is a much more scalable option than the others. Web farm architecture can very easily access the session variables because they are stores in an independent database.
Reliability: Because the data is physically persisted in a database, it is is more reliable than the other options. It has the ability to survive server restarts.
Security: SQL Server is more secure than the in-memory or state server option. You can protect your data more easily by configuring SQL Server security.

这是一篇旧文章,但这些原则仍然适用。

使用 Web 服务器内存时可能会出现问题。

How does increasing the session timeout effect the application performance and why?

If you extend the duration of Sessions, any items held in session variables will stay in memory on the server longer. Depending on how busy your application is, and the type and number of items you persisits as session variables, this may degrade performance.

从引用中复制了错别字。

这个问题还讨论了会话状态和使用 cookie 之间的区别 FormsAuthentication

Should I use Session State or FormAuthentication to keep track of a signed-in user?

因此,根据您使用的身份验证类型 - 您可以使用 cookie 路线,请记住,用户可以从浏览器中删除 cookie,这将使他们注销。

这是另一个对文档有帮助的 link。

Securing Session State

使用为身份验证选择的个人用户帐户从头开始创建了一个普通 MVC 项目。

Startup.Auth.cs

public partial class Startup {
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app) {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            },
            ExpireTimeSpan = TimeSpan.FromDays(7)//<-- I just added this.
        });

        //...code removed for brevity
    }
}
// Summary:
//     Controls how much time the cookie will remain valid from the point it is
//     created. The expiration information is in the protected cookie ticket. Because
//     of that an expired cookie will be ignored even if it is passed to the server
//     after the browser should have purged it
public TimeSpan ExpireTimeSpan { get; set; }

项目中没有任何其他更改,默认模板提供了所需的一切。

更新

根据评论,您始终可以将其添加为 web.config 中的应用程序设置并使用 ConfigurationManager 访问它。这样就可以修改它而不必重新编译代码。

var expireTimeSpan = TimeSpan.FromDays(7);//the default
var setting = ConfigurationManager.AppSettings["ApplicationCookieExpireTimeInDays"];
if (setting != null) {
    var days = 0;
    if (int.TryParse(setting, out days)) {
        expireTimeSpan = TimeSpan.FromDays(days);
    }
}

// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions {
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.  
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    },
    ExpireTimeSpan = expireTimeSpan
});

其中 web.config 将保留设置。

<appSettings>
  <add key="webpages:Version" value="3.0.0.0" />
  <add key="webpages:Enabled" value="false" />
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  <add key="ApplicationCookieExpireTimeInDays" value="14" />
</appSettings>