
1 // ----------------------------------------------------------------------- 2 // <copyright file="CustomExceptionAttribute.cs" company="技術支持——譚明超"> 3 // Copyright (c) 2016 QS.Web.Extensions. All rights reserved. 4 // </copyright> 5 // <last-editor>譚明超</last-editor> 6 // <last-date>2016/8/2 20:56:16</last-date> 7 // ----------------------------------------------------------------------- 8 9 using System; 10 using System.Web; 11 using System.Web.Mvc; 12 13 namespace QS.Web.Extensions 14 { 15 public class CustomExceptionAttribute : FilterAttribute, IExceptionFilter 16 { 17 public void OnException(ExceptionContext filterContext) 18 { 19 Exception exception = filterContext.Exception; 20 if (filterContext.ExceptionHandled == true) 21 { 22 return; 23 } 24 HttpException httpException = new HttpException(null, exception); 25 //filterContext.Exception.Message可獲取錯誤信息 26 27 /* 28 * 1、根據對應的HTTP錯誤碼跳轉到錯誤頁面 29 * 2、這里對HTTP 404/400錯誤進行捕捉和處理 30 * 3、其他錯誤默認為HTTP 500服務器錯誤 31 */ 32 if (httpException != null && (httpException.GetHttpCode() == 400 || httpException.GetHttpCode() == 404)) 33 { 34 filterContext.HttpContext.Response.StatusCode = 404; 35 filterContext.HttpContext.Response.Write("錯誤的請求路徑"); 36 filterContext.HttpContext.Response.WriteFile("~/HttpError/404.html"); 37 } 38 else 39 { 40 filterContext.HttpContext.Response.StatusCode = 500; 41 filterContext.HttpContext.Response.Write("服務器內部錯誤"); 42 filterContext.HttpContext.Response.WriteFile("~/HttpError/500.html"); 43 } 44 /*--------------------------------------------------------- 45 * 這里可進行相關自定義業務處理,比如日志記錄等 46 ---------------------------------------------------------*/ 47 48 //設置異常已經處理,否則會被其他異常過濾器覆蓋 49 filterContext.ExceptionHandled = true; 50 51 //在派生類中重寫時,獲取或設置一個值,該值指定是否禁用IIS自定義錯誤。 52 filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; 53 } 54 } 55 }
該源碼源自網上,,,,不記得哪里的了