Asp.net-Mvc
如果拋出自定義異常,則重定向 asp.net mvc
如果在我的應用程序中引發自定義錯誤,我需要全域重定向我的使用者。我嘗試將一些邏輯放入我的 global.asax 文件中以搜尋我的自定義錯誤,如果它被拋出,則執行重定向,但我的應用程序從未命中我的 global.asax 方法。它一直給我一個錯誤,說我的異常未被使用者程式碼處理。
這就是我在全球範圍內所擁有的。
protected void Application_Error(object sender, EventArgs e) { if (HttpContext.Current != null) { Exception ex = HttpContext.Current.Server.GetLastError(); if (ex is MyCustomException) { // do stuff } } }我的異常拋出如下:
if(false) throw new MyCustomException("Test from here");當我從拋出異常的文件中將其放入 try catch 中時,我的 Application_Error 方法永遠不會被呼叫。有人對我如何在全球範圍內處理這個問題(處理我的自定義異常)有一些建議嗎?
謝謝。
2010 年 1 月 15 日編輯:這是 // 做的東西。
RequestContext rc = new RequestContext(filterContext.HttpContext, filterContext.RouteData); string url = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { Controller = "Home", action = "Index" })).VirtualPath; filterContext.HttpContext.Response.Redirect(url, true);
您想為您的控制器/操作創建一個客戶過濾器。您需要從
FilterAttributeand繼承IExceptionFilter。像這樣的東西:
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter { public void OnException(ExceptionContext filterContext) { if (filterContext.Exception.GetType() == typeof(MyCustomException)) { //Do stuff //You'll probably want to change the //value of 'filterContext.Result' filterContext.ExceptionHandled = true; } } }一旦你創建了它,你就可以將該屬性應用到一個 BaseController 上,你的所有其他控制器都繼承自它,以使其具有站點範圍的功能。
這兩篇文章可能會有所幫助: