asp.net web api中介紹一個程序中操作(登錄、登出、增加、修改、刪除等等)日誌記錄功能的實現

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()]就大功告成了。

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