C# 会话过期时重定向到登录页面的最佳实践

C# 会话过期时重定向到登录页面的最佳实践,c#,asp.net-mvc,session,asp.net-mvc-5,owin,C#,Asp.net Mvc,Session,Asp.net Mvc 5,Owin,如果会话过期,我想将用户重定向到登录页面。我发现有很多方法可以做到这一点,但在ASP.NETMVC5和OWIN中,什么是最好的(或默认的)方法? 可能是开箱即用?但是怎么做呢 剃刀: 在有效登录后设置会话变量 将此添加到_Layout.cshtml中: @if(会话[“IsLogin”]==null) { 会话。放弃(); 重定向(“~/LoginControllerName/LoginActionName”); } Global.asax: 可以使用这两种方法,但我不知道如何使用 受

如果会话过期,我想将用户重定向到登录页面。我发现有很多方法可以做到这一点,但在ASP.NETMVC5和OWIN中,什么是最好的(或默认的)方法? 可能是开箱即用?但是怎么做呢

剃刀:

  • 在有效登录后设置会话变量
  • 将此添加到_Layout.cshtml中:
@if(会话[“IsLogin”]==null)
{
会话。放弃();
重定向(“~/LoginControllerName/LoginActionName”);
}
Global.asax:

  • 可以使用这两种方法,但我不知道如何使用
受保护的无效会话\u启动(对象发送方,事件参数e)
{
//启动新会话时运行的代码
}
受保护的无效会话\u结束(对象发送方,事件参数e)
{
//会话过期时运行的代码
}
我当前的解决方案:

  • 所有控制器继承自
    BaseController
  • 我使用了OnAuthorizationAttribute,因为只有当它是非公共页面时才应该执行重定向
公共抽象类BaseController:控制器
{
授权时受保护的覆盖无效(AuthorizationContext filterContext)
{
if(this.Session[“RedirectAfterLogin”]==null)
{
var isAnonymousAllowed=filterContext.ActionDescriptor.IsDefined(typeof(AllowOnyMousAttribute),true)| | filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowOnyMousAttribute),true);
如果(!不允许)
{
this.Session[“RedirectAfterLogin”]=this.Request.Url?.ToString();
filterContext.Result=this.RedirectToAction(“LoginActionName”、“LoginControllerName”);
}
}
基于授权(filterContext);
}
}
  • 重定向后,注销用户:
if(this.AuthenticationManager==null)
{
this.SetAuthenticationManager(this.HttpContext?.GetOwinContext()?.Authentication);
}
this.AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationOkie);
  • 有效登录后设置会话变量:
this.Session[“RedirectAfterLogin”]=this.Request.Url?.ToString();

您可以在mvc5中使用owin的默认启动

 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);
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {

                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });            
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

    }
}
公共部分类启动
{
//有关配置身份验证的详细信息,请访问http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder应用程序)
{
//将数据库上下文、用户管理器和登录管理器配置为每个请求使用一个实例
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext(ApplicationUserManager.Create);
app.CreatePerOwinContext(ApplicationSignInManager.Create);
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationType=DefaultAuthenticationTypes.ApplicationOkie,
LoginPath=新路径字符串(“/Account/Login”),
Provider=新CookieAuthenticationProvider
{
OnValidateIdentity=SecurityStampValidator.OnValidateIdentity(
validateInterval:TimeSpan.FromMinutes(30),
regenerateIdentity:(管理器,用户)=>user.GenerateUserIdentityAsync(管理器))
}
});            
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
//允许应用程序在验证双因素身份验证过程中的第二个因素时临时存储用户信息。
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie,TimeSpan.FromMinutes(5));
app.useTowFactoryMemberBrowserCookie(DefaultAuthenticationTypes.TwoFactoryRememberBrowserCookie);
}
}

使用自定义
CookieAuthenticationProvider
可以处理过期会话后的重定向以及当前页面等附加信息

公共部分类启动
{
//有关配置身份验证的详细信息,请访问http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder应用程序)
{
//将数据库上下文、用户管理器和登录管理器配置为每个请求使用一个实例
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext(ApplicationUserManager.Create);
app.CreatePerOwinContext(ApplicationSignInManager.Create);
var url=newURLhelper(HttpContext.Current.Request.RequestContext);
var provider=新CookieAuthenticationProvider();
var originalHandler=provider.OnApplyRedirect;
provider.OnApplyRedirect=上下文=>
{
var routeValues=新的RouteValueDictionary();
var uri=新uri(context.RedirectUri);
var returnUrl=HttpUtility.ParseQueryString(uri.Query)[context.Options.ReturnUrlParameter];
添加(context.Options.ReturnUrlParameter,returnUrl);
context.RedirectUri=url.Action(“登录”、“帐户”、路由值);
调用(上下文);
};
provider.OnValidateIdentity=SecurityStampValidator.OnValidateIdentity(
validateInterval:TimeSpan.FromMinutes(30),
regenerateIdentity:(管理器,用户)=>user.GenerateUserIdentityAsync(管理器));
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationType=DefaultAuthenticationTypes.ApplicationOkie,
LoginPath=新路径字符串(“/Account/Login”),
提供者=提供者,
slidengexpiration=true,
ExpireTimeSpan=时间跨度从分钟(30)
});            
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
//允许应用程序在验证tw中的第二个因素时临时存储用户信息