1)创建类BaseController.cs ,继承Controller类并重写OnException方法,代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication70.Controllers
{
public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
// 错误日志编写
string controllerNamer = filterContext.RouteData.Values["controller"].ToString();
string actionName = filterContext.RouteData.Values["action"].ToString();
string exception = filterContext.Exception.ToString();
Sys_Log logEntity = new Sys_Log
{
LogID = Guid.NewGuid().ToString(),
LogType = LintwayCommon.MyEnum.LogType.ErrorLog.ToString(),
OperationDate = DateTime.Now,
ControllerName = controllerNamer,
ActionName = actionName,
Content = exception,
CreateDate = DateTime.Now,
ModifyDate = DateTime.Now,
Status = ((int)LintwayCommon.MyEnum.Status.Valid).ToString()
};
_logServer.AddEntity(logEntity);
// 表示异常已处理
filterContext.ExceptionHandled = true;
// 执行基类中的OnException
base.OnException(filterContext);
}
}
}
2)然后其他需要记录日志的Controller继承BaseController即可
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication70.Controllers
{
public class HomeController : BaseController
{
public ActionResult Index()
{
string test1 = "a";
int test2 = Int32.Parse(test1);
return View();
}
}
}