asp.Netmvcでグローバル例外フィルタを構成する

9071 ワード

ステップ1:クラスの定義:MyHandlerErrorAttribute継承HandleErrorAttribute
OnExceptionメソッドの書き換え
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text;
namespace TimeRecord.Models
{
    public class MyHandlerErrorAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
         //1.      
            Exception ex = filterContext.Exception;
            //2.           
            string strController = filterContext.RouteData.Values["controller"].ToString();
            string strAction = filterContext.RouteData.Values["action"].ToString();
            //3.      
            string errMsg = String.Format("   :{0};Action:{1};    :{2};", strController, strAction, ex.ToString());
            WtLog(errMsg);
            //        
            filterContext.Result = new RedirectResult("/TimeRecord/error");
            //          
            filterContext.ExceptionHandled = true;
            base.OnException(filterContext);
        }
        public void WtLog(string message) 
        
      {
          string path = AppDomain.CurrentDomain.BaseDirectory + "\\log\\log.txt";
            
          using (StreamWriter sw = new StreamWriter(path,true,Encoding.Default  ))
          {
              sw.Flush();//             ,              。
              sw.WriteLine("" + DateTime.Now);
              sw.WriteLine("" + message);
              sw.WriteLine("=======");
          }
        
        }
    }
}

ステップ2 filterConfigにカスタムMyHandlerErrorAttributeを追加
using System.Web;
using System.Web.Mvc;
using TimeRecord.Models;

namespace TimeRecord
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new MyHandlerErrorAttribute());
        }
    }
}

ステップ3はWebでconfigにsystemを配置する.Webノードの下
    "On">

ステップ4テスト
コントローラに例外を作成
   #region     
      [HttpGet]

       public ActionResult UserTimeRecord()


     {
         int a = 0;
         int b = 1 / a;

         
          
        }
 
  
        #endregion

ログフォルダが表示されるとログファイルが生成されます
=======
  :2019/7/31 10:08:17
  :   :TimeRecord;Action:UserTimeRecord;    :System.DivideByZeroException:      。
     TimeRecord.Controllers.TimeRecordController.UserTimeRecord()    c:\Users\Administrator\Desktop\   \study\TimeRecord\TimeRecord\Controllers\TimeRecordController.cs:   198
     lambda_method(Closure , ControllerBase , Object[] )
     System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
     System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
     System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
     System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.b__41()
     System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.b__7(IAsyncResult _)
     System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
     System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
     System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.b__33()
     System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.b__49()
     System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.b__36(IAsyncResult asyncResult)
     System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
     System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
     System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<>c__DisplayClass2a.b__20()
     System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.b__22(IAsyncResult asyncResult);
=======

  
転載先:https://www.cnblogs.com/Vinkong/p/11274633.html