我目前使用ASP.NET MVC应用程序的默认表单身份验证方法。
在我需要身份验证的所有动作方法之上,我有这个属性
[Authorize()]
当有人试图调用该操作方法“服务”并且尚未登录的页面时,它会将它们发送到登录页面...完美!但是,如果他们的会话超时并且他们试图点击该页面,他们也只是被重定向到登录页面而没有指示原因。我希望能够确定它是否是新访问,或者是否超时并在登录屏幕上显示相应的消息。
这可能吗?
答案 0 :(得分:2)
看看我所做的这个自定义授权属性。它是为了实现一些基于角色的自定义授权,但您也可以使它适用于您。有一个Session.IsNewSession属性,您可以检查此请求是否发生在新会话上。
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.User.Identity.IsAuthenticated)
{
httpContext.User = new GenericPrincipal(httpContext.User.Identity, AdminUserViewModel.Current.SecurityGroups.Select(x => x.Name).ToArray());
}
return base.AuthorizeCore(httpContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectResult("/Authentication/NotAuthorized", false);
}
else
{
if (filterContext.HttpContext.Session.IsNewSession)
{
// Do Something For A New Session
}
base.HandleUnauthorizedRequest(filterContext);
}
}
}
答案 1 :(得分:0)
登录后,您可以设置与浏览器会话相关联的Cookie。如果该cookie存在,您知道会话超时。如果没有,你知道这是一次新的访问。