首先我们要了解MVC提供了4种常用的拦截器:IActionFilter(Action拦截器接口)、IExceptionFilter(异常拦截器接口)、IResultFilter(Result拦截器接口)、IAuthorizationFilter(授权拦截器接口)
1.建一张保存操作日志的表
create table system_log
(
Id char(32) primary key,
UserId char(32) not null comment '用户Id',
UserName varchar(50) not null comment '用户名称',
Tkey varchar(20) not null comment '关键字',
Description varchar(100) not null comment '操作描述',
OperateResult int default 0 not null comment '操作结果.0,失败;1,成功;',
DateTime datetime not null comment '操作时间'
) comment '系统日志';
2.实现IActionFilter接口(Action拦截器接口),这里定义了2个参数Key和Description,分别表示操作的关键字和描述,方便分类查询和展示
/// <summary>
/// 操作日志拦截器
/// </summary>
public class LoggerFilter : FilterAttribute, IActionFilter
{
/// <summary>
/// 日志关键字
/// </summary>
public string Key { get; set; } /// <summary>
/// 日志描述
/// </summary>
public string Description { get; set; } /// <summary>
/// Action执行后
/// </summary>
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
var result = ((System.Web.Mvc.JsonResult)filterContext.Result).Data.ToString(); var logService = new Service.SystemLogService(); var model = new Data.DomainModels.SystemLog()
{
UserId = "管理员Id",
UserName = "管理员名称",
Tkey = Key,
Description = Description,
OperateResult = result.Contains("True") ? 1 : 0,
}; logService.Save(model);
} /// <summary>
/// Action执行前
/// </summary>
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{ }
}
3.使用日志拦截器,在需要记录操作日志的Action上加上拦截器属性就OK了,麻烦的是需要给每个Action定义Key和Description
/// <summary>
/// 日志拦截器测试
/// </summary>
[LoggerFilter(Key = "key", Description = "做了哪些事情")]
public ActionResult DoSomething(string param)
{
//具体业务逻辑 return JRCommonHandleResult(true);
}