2012-10-17 45 views
1

我有一個混合(同時使用MVC和傳統的ASP頁面)ASP(C#)網中的應用 和需要實現共同的錯誤處理兩個MVC和遺留代碼; 即,我必須檢測無效URL和重新路由的無效的請求到 要麼主頁或登錄頁面(取決於用戶是否登錄或沒有)。對於一些無效的請求,會話對象變爲空

我已經添加了「的Application_Error」內的錯誤處理碼(參見下面的代碼)。

的問題如下:的loggedIn用戶ID保存在Session對象 和一些無效的網址中包含會話對象變爲空着:「會話狀態不是在這種情況下可用」

例如:

以下網址,會話對象存在:

1. http://myserver:49589/test/home/index 
2. http://myserver:49589/test/home/in 
3. http://myserver:49589/test/ho 

但對於下面的網址,會話對象爲空:

4. http://myserver:49589/te 

所以,問題是,爲什麼當我在請求拼錯的文件夾名稱會話對象變成空的,我怎麼能解決這個問題。

路由圖如下:

context.MapRoute(
    "default", 
    "test/{controller}/{action}/{id}", 
    new { action = "Index", id = UrlParameter.Optional } 
); 


protected void Application_Error(object sender, EventArgs e) 
{ 
    Exception exception = Server.GetLastError(); 
    Response.Clear(); 

    HttpException httpException = exception as HttpException; 
    if (httpException != null) // Http Exception 
    { 
     switch (httpException.GetHttpCode()) 
     { 
      case 400: // Bad Request 
      case 404: // Page Not Found 
      case 500: // Internal Server Error 
       { 
        // Clear the error on server. 
        Server.ClearError(); 

        ServerConfiguration scfg = ServerConfiguration.Instance; 
        if (ConnxtGen.App.AppUtility.GetCurrentUserID() != -1) 
        { 
         Response.RedirectToRoute("Unity_default", new { controller = "Home", action = "Index" }); 
        } 
        else 
        { 
         Response.Redirect(scfg.PagePath + "/login/login.aspx", false); 
        } 
        break; 
       } 
      default: 
       { 
        break; 
       } 
     } 
    } 
    // Avoid IIS7 getting in the middle 
    Response.TrySkipIisCustomErrors = true; 
} 

回答

1

有一件事你應該明白的是,會話變量是唯一可用的HttpApplication.AcquireRequestState事件發生後。

在你的問題,要獲取會話中的一些信息的時刻是在Asp.Net頁面生命週期的過程中過早。

我發現這個職位必將更好地解釋當會話對象將可用:

Asp.net What to do if current session is null?

這裏是在更深的細節解釋Asp.Net頁面的整個內部流程一大篇生命週期:

ASP.NET Application and Page Life Cycle