如果会话过期,我想将用户重定向到登录页面 . 我发现有很多方法可以做到这一点,但是ASP.Net MVC5中使用OWIN的最佳(或默认)方式是什么?可能它开箱即用?但是怎么样?
剃刀:
-
在有效登录后设置会话变量
-
在_Layout.cshtml中添加:
@if (Session["IsLogin"] == null)
{
Session.Abandon();
Response.Redirect("~/LoginControllerName/LoginActionName");
}
Global.asax中:
- 可以使用这两种方法,但我不知道如何使用 .
protected void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
protected void Session_End(object sender, EventArgs e)
{
// Code that runs when a session is expired
}
我目前的解决方案
-
所有控制器都继承自
BaseController
-
我使用了OnAuthorizationAttribute,因为只有在非公共页面时才会执行重定向 .
public abstract class BaseController : Controller
{
protected override void OnAuthorization(AuthorizationContext filterContext)
{
if (this.Session["RedirectAfterLogin"] == null)
{
var isAnonymousAllowed = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
if (!isAnonymousAllowed)
{
this.Session["RedirectAfterLogin"] = this.Request.Url?.ToString();
filterContext.Result = this.RedirectToAction("LoginActionName", "LoginControllerName");
}
}
base.OnAuthorization(filterContext);
}
}
- 重定向后退出用户:
if (this.AuthenticationManager == null)
{
this.SetAuthenticationManager(this.HttpContext?.GetOwinContext()?.Authentication);
}
this.AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
- 有效登录后设置会话变量:
this.Session["RedirectAfterLogin"] = this.Request.Url?.ToString();
2 回答
您可以在mvc5中使用owin的默认启动
过期会话后的重定向以及当前页面等其他信息可以使用自定义
CookieAuthenticationProvider
进行处理 .