Asp.net mvc 笔记

捕捉处理全局异常

自定义一个Attribute继承默认的HandleErrorAttribute

namespace EmpowerApiService.Filter
{
    public class CustomerErrorAttribute : HandleErrorAttribute
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled) { return; }


            var controllerName = (string)filterContext.RouteData.Values["controller"];
            var actionName = (string)filterContext.RouteData.Values["action"];
            var error = new { 
                message = filterContext.Exception.Message,
                hresult = filterContext.Exception.HResult.ToString("X")
            } ;

            if (filterContext.HttpContext != null && filterContext.HttpContext.Request != null)
            {
                var requestUrl = filterContext.HttpContext.Request.Url.ToString();
                var requestParams = filterContext.HttpContext.Request.Params;
                var requestParamsStr = HttpUtility.UrlDecode(requestParams.ToString());

                // 
                logger.Error(
                    filterContext.Exception,
                    "url: {0}, params: {1}",
                    new Object[] {requestUrl, requestParamsStr });
            }

            filterContext.ExceptionHandled = true;

            // request side error
            if (filterContext.Exception is ArgumentException)
            {
                filterContext.HttpContext.Response.StatusCode = 400;
            }
            // server side error
            else
            {
                filterContext.HttpContext.Response.StatusCode = 500;
            }
            // build http response
            filterContext.Result = new JsonResult() { ContentType = "applicaltion/json", ContentEncoding = System.Text.Encoding.UTF8, Data = error, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }
}

注册自定义的处理类,使之生效,替换默认的错误处理,修改APP_Start中的FilterConfig.cs

namespace EmpowerApiService
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            //filters.Add(new HandleErrorAttribute());
            filters.Add(new EmpowerApiService.Filter.CustomerErrorAttribute());
        }
    }
}

在需要使用错误处理的ControllerAction上使用特性,就可以捕捉并处理异常

using EmpowerApiService.Filter;

namespace EmpowerApiService.Controllers{

   [CustomerError]
   public class xxxController : Controller{ ... }
}

使用日志组件 NLog

先从Nuget安装NLog,网文说要同时安装NLog.Config,经实测不安装也可以,测试版本是5.2.3
右键点击目标项目,新增项,选择新增配置文件,起名NLog.config
image

编辑文件如下

<?xml version="1.0"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	  xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd"
	  autoReload="true"
	  throwException="false"
	  internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

	<variable name="appName" value="EmpowerApiService" />
	
	<targets>
		<target name="logfile" 
				xsi:type="File"
				fileName="${basedir}/logs/${appName}-${shortdate}.log"
				layout="${longdate}|${uppercase:${level}}|${message}${newline}${callsite}(${callsite-filename:includeSourcePath=False}:${callsite-linenumber})|${exception:format=ToString}"
				maxArchiveFiles="999"
				archiveFileName="${basedir}/logs/${appName}-${shortdate}-${###}.log"
				createDirs="true"
				archiveAboveSize="5242880"
				archiveEvery="Day"
				archiveNumbering="Sequence"
				encoding="UTF-8"
				>
		</target>
	</targets>

	<rules>
		<logger name="*" minlevel="Debug" writeTo="logfile"/>
	</rules>
</nlog>

在需要使用日志的类中实例化日志组件即可使用
image

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章