1、首先建一个拦截器类继承自System.Web.Mvc.FilterAttribute和System.Web.Mvc.IActionFilter:代码如下
namespace aaa
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class LogAttribute : System.Web.Mvc.FilterAttribute,System.Web.Mvc.IActionFilter
{
string model = "";
private Dictionary<string, string> parmsObj = null;
public void OnActionExecuting(ActionExecutingContext filterContext)
{
//中间主要操作删除功能,用来返回删除的id名称
//获取action名称
string actionName = filterContext.ActionDescriptor.ActionName;
//获取controller的名称
string controllerName =
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
//定义一个key\value值的参数字典
parmsObj = new Dictionary<string, string>();
parmsObj = GetParmsList(filterContext);
if (actionName == "方法名")
{
if (controllerName == "学生控制器名")
{
//实现工厂接口
IFactorylog factorylog = new StudentLog();
//根据id获取这条信息的内容
model = factorylog.GetModel(parmsObj["id"]);
}
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
//大部分操作都在这里
//获取Controller 名称
string controllerName =
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
//获取请求的ip地址
string IP = GetClientLocalIPv4Address(filterContext);
if (controllerName == "登录的控制器")
{
//登录实现
IFactorylog factorylog = new LoginLog();
factorylog.CreateLog(filterContext, IP,"", parmsObj);
} else if (controllerName == "学生控制器名")
{
IFactorylog factorylog = new StudentLog();
factorylog.CreateLog(filterContext, IP, model, parmsObj);
}
}
/// <summary>
/// 获取客户端内网IPv4地址
/// </summary>
/// <returns>客户端内网IPv4地址</returns>
public static string GetClientLocalIPv4Address(ActionExecutedContext filterContext)
{
string userHostAddress =
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(userHostAddress))
{
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] !=null)
{ userHostAddress =
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',' )[0].Trim();
}
if (string.IsNullOrEmpty(userHostAddress))
{
userHostAddress = HttpContext.Current.Request.UserHostAddress;
}
return userHostAddress;
}
/// <summary>
/// 获取请求参数
/// </summary>
/// <param name="filterContext"></param>
/// <returns></returns>
private Dictionary<string, string> GetParmsList(ActionExecutingContext filterContext)
{
Dictionary<string, string> parmsObj = new Dictionary<string, string>();
try
{
//请求类各个字段的值
foreach (var item in filterContext.ActionDescriptor.GetParameters())
{
var itemType = item.ParameterType;
if (itemType.IsClass && itemType.Name != "String")
{
PropertyInfo[] infos = itemType.GetProperties();
foreach (PropertyInfo info in infos)
{
if (info.CanRead)
{
var propertyValue = filterContext.Controller.ValueProvider.GetValue(info.Name);// 暂不支持多层嵌套 后期优化?
if (!parmsObj.ContainsKey(info.Name))
{
parmsObj.Add(info.Name, null == propertyValue ? "" :
propertyValue.AttemptedValue);
}
}
}
}
else
{
var parameterValue = filterContext.Controller.ValueProvider.GetValue(item.ParameterName);
if (!parmsObj.ContainsKey(item.ParameterName))
{
parmsObj.Add(item.ParameterName, null == parameterValue ? "" : parameterValue.AttemptedValue);
}
}
}
}
catch (Exception)
{
return null;
}
return parmsObj;
}
}
}
实现类的代码如下:
public class StudentLog : IFactorylog
{
public void CreateLog(ActionExecutedContext filterContext, string IP, string modelstr,Dictionary<string, string> parmsObj)
{
//获取action名称
string actionName = filterContext.ActionDescriptor.ActionName;
//获取Controller 名称
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
string UpdateMsg = "";
///失败不添加
if (actionName != "导出方法名")
{
JsonResult response = filterContext.Result as JsonResult;
JsonResponse json = response.Data as JsonResponse;
UpdateMsg = json.UpdateMsg;
if (json.m!= 0)
{
return;
}
}
string strDescription = "";
string strLevel = "";
if (parmsObj.Count > 1)
{
if (parmsObj["ID"] != null && parmsObj["ID"] == "0")
{
strLevel = "新增";
strDescription += strLevel + "证件号码为" + parmsObj["IDCARD"] + "的考生信息";
}
else
{
strLevel = "更新";
strDescription += strLevel + "证件号码为" + parmsObj["IDCARD"] + "的考生信息:"+ UpdateMsg.TrimEnd(',');
}
}
else if (parmsObj.Count == 1)
{
strLevel = "删除";
strDescription += strLevel + modelstr + "的考生信息";
}
else
{
if(actionName== "导出方法名")
{
strLevel = "导出";
}
else
{
return;
}
}
//记录日志类
S_SYSLOG_SC s_SYSLOG_SC = new S_SYSLOG_SC();
S_OperateLog operateLog = new S_OperateLog();
operateLog.OP_ID = Guid.NewGuid();//ip地址
operateLog.OP_TIME = DateTime.Now;//时间
operateLog.OP_DESCRIPTION = strDescription;//描述
operateLog.OP_LEVEL = strLevel;//级别
operateLog.OP_LOGINNAME = 操作人
operateLog.OP_ROLENAME = 角色名
operateLog.OP_MODELNAME = 那个模块
operateLog.OP_IP = IP;
//插入数据库里
}
public string GetModel(string Model)
{
string result = "";
if (Model.Contains(",")) //删除多条信息
{
result = "证件号码为:";
foreach (var item in Model.Split(','))
{
//获取这条信息
if (model != null)
{
result += model.IDCARD+",";
}
}
result = result.TrimEnd(',');
}
else //删除一条信息
{
//获取这条信息
if (model != null)
{
result = "证件号码为" + model.IDCARD;
}
}
return result;
}
}
然后在每个方法名上加入[LogAttribute()]就大功告成了。