2011-11-21 99 views
4

我目前對我的ASP.NET MVC應用程序使用默認窗體身份驗證方法。ASP.NET MVC 3確定會話狀態(新建或超時)

首先我actionmethods的需要身份驗證我有這個屬性

[Authorize()] 

當有人試圖調用頁面這一行動方法「服務」而他們還沒有登錄,這將它們發送到登錄頁面...完美!但是,如果他們的會話超時並嘗試打開該頁面,則他們也會被重定向到登錄頁面,而不會顯示原因。我希望能夠確定它是否是新的訪問,或者是否是超時,並相應地在登錄屏幕上顯示不同的消息。

這可能嗎?

回答

0

在登錄時,您可以設置一個與瀏覽器會話綁定的cookie。如果該cookie存在,則知道會話超時。如果不是,你知道這是一次新的訪問。

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); 
      } 
     } 
    }