2011-08-17 20 views
2

我看到一個很好的例子,其中的MVC控制器類從處理異常和內返回,像這樣與該錯誤的另外一個控制器類繼承:如何確保我的MVC應用程序在發生某種異常時重定向到錯誤頁面?

public class ApplicationController : Controller 
{ 
    public ActionResult NotFound() 
    { 
     return View("NotFound"); 
    } 

    public ActionResult InsufficientPriveleges() 
    { 
     return View("InsufficientPriveleges"); 
    } 

    protected override void OnException(ExceptionContext filterContext) 
    { 
     if (filterContext.Exception is NotFoundException) 
     { 
      filterContext.Result = NotFound(); 
      filterContext.ExceptionHandled = true; 
      return; 
     } 
     if (filterContext.Exception is InsufficientPrivelegesException) 
     { 
      filterContext.Result = InsufficientPriveleges(); 
      filterContext.ExceptionHandled = true; 
      return; 
     } 

     base.OnException(filterContext); 
    } 
} 

不過,我已經注意到,例如說我的控制器正在部分視圖中加載用戶不應訪問的內容,錯誤將顯示在頁面上的部分視圖中。

我希望整個頁面顯示錯誤,實際上,異常應該重定向到一個全新的頁面。我如何使用上面顯示的當前課程來實現這一目標?

+0

我認爲這會回答你的問題:http://stackoverflow.com/questions/550995/get-filter-redirect-to-action –

+0

我似乎不能扔孩子的行動中一個例外。我認爲我需要能夠在服務層的任何位置拋出一個異常,而不管我在渲染管道中的哪個位置,並讓其重新進行。有任何想法嗎? – jaffa

+0

您介意顯示有問題的局部視圖和相關操作嗎?也許它處理正確的情況下部分視圖... –

回答

2

你可以在你的web.config創建HTTP結果代碼特定錯誤處理程序映射:

<customErrors mode="On" defaultRedirect="~/Error"> 
    <error statusCode="401" redirect="~/Error/Unauthorized" /> 
    <error statusCode="404" redirect="~/Error/NotFound" /> 
</customErrors> 

,然後創建一個自定義錯誤控制器

public class ErrorController 
{ 
     public ActionResult Index() 
     { 
      return View ("Error"); 
     } 

     public ActionResult Unauthorized() 
     { 
      return View ("Error401"); 
     } 

     public ActionResult NotFound() 
     { 
      return View ("Error404"); 
    } 
    } 

再扔從HttpException您的控制器

public ActionResult Test() 
{ 
    throw new HttpException ((int)HttpStatusCode.Unauthorized, "Unauthorized"); 
} 

另一種選擇是使用cu自定FilterAttribute檢查哪些不同拋出一個HttpException

[Authorize (Roles = SiteRoles.Admin)] 
public ActionResult Test() 
{ 
    return View(); 
} 
+0

看到我的評論上面關於拋出兒童行爲異常。 – jaffa

+0

更新:上述工作,但我可能會補充說,如果您想要有效地呈現新的錯誤頁面,則嘗試在控制器上的子操作內引發異常會導致問題。我反而從控制器上的主要操作中檢查並引發異常,而不是任何子操作。 – jaffa

0

你必須處理Ajax調用的權限。我只是簡單地使用jquery $ .ajax的error()來處理那種ajax調用錯誤。

$.ajax({ 
    ... 
    success: function(g) { 
      //process normal 
    }, 
    error: function(request, status, error) { 
      //process exception here 
    } 
}) 
相關問題