2010-08-03 45 views
0

我有一個ASP.NET MVC2應用程序,它使用父控制器來設置在應用程序周圍使用的特定變量。我還實現了驗證,以確保數據庫中存在URI中的ID。如果沒有,我重定向並停止腳本的執行。ASP.NET MVC2父控制器不重定向

我父控制器看起來是這樣的:


// Inside class declaration 

// Set instance of account object to blank account 
protected Account account = new Account(); 

protected override void Initialize(System.Web.Routing.RequestContext requestContext) { 
    // Call parent init method 
    base.init(requestContext); 

    // Check to make sure account id exists 
    if (accountRepos.DoesExistById(requestContext.RouteData.Values["aid"].ToString()) { 
     account = accountRepos.GetById(requestContext.RouteData.Values["aid"].ToString()); 
    } else { 
     requestContext.HttpContext.Response.Redirect("url"); 
     requestContext.HttpContext.Response.End(); 
    } 
} 

起初,這個工作,但輸入了不正確的ID現在時,它不會重定向和使用賬戶類時拋出一個NullPointerException。我最初只是聲明帳戶變量而非實例化它,但也證明會拋出異常並且不會重定向。

我試圖結束腳本執行的原因是因爲我想確保即使重定向不起作用它也會停止。有點像在PHP中的header()之後調用exit():p。如果我做錯了,我會很感激任何指針。

我只是想知道如何解決這個問題。

任何幫助是極大的讚賞= d

回答

1

我不認爲這是應該做你想要什麼的正確方法。相反,你應該在你的路線上使用路線約束來確保id存在,並從那裏以「全部捕捉」路線回落。

事情是這樣的:

Routes.MapRoute("Name", "Url", new { ... }, new { 
    Id = new IdConstraint() // <- the constraint returns true/false which tells the route if it should proceed to the action 
}); 

的約束是這樣的:

public class IdConstraint : IRouteConstraint { 
    public bool Match(
     HttpContextBase Context, 
     Route Route, 
     string Parameter, 
     RouteValueDictionary Dictionary, 
     RouteDirection Direction) { 
     try { 
      int Param = Convert.ToInt32(Dictionary[Parameter]); 

      using (DataContext dc = new DataContext() { 
       ObjectTrackingEnabled = false 
      }) { 
       return (dc.Table.Any(
        t => 
         (t.Id == Param))); 
      }; 
     } catch (Exception) { 
      return (false); 
     }; 
    } 
} 

這是我和我的路由使用,以確保我收到的ID真的存在。如果它不存在,那麼約束返回false,並且路由不執行,並且請求繼續沿着路由鏈。在路由的最底層,你應該有一個通用的捕獲所有路由,把你的用戶發送到一個頁面,告訴他們他們想要的東西不存在,並執行X或X(這些行中的東西,我只是來了與情景)。

+0

+1有趣的解決方案;我正要推薦一個自定義的授權過濾器,但我更喜歡IRouteContraint – Tahbaza 2010-08-03 23:41:12

+0

太棒了!我會試試這個。 – Swamp56 2010-08-04 00:01:51

+0

我閱讀了IRouteConstraint接口並實現了自己的約束類,它工作正常! – Swamp56 2010-08-04 02:26:33

相關問題