方法
public class MyActionFilter : IActionFilter { public static readonly log4net.ILog logger = log4net.LogManager.GetLogger("InfoLog"); /// <summary> /// 加载视图后执行 /// </summary> /// <param name="filterContext"></param> public void OnActionExecuted(ActionExecutedContext filterContext) { //throw new NotImplementedException(); } /// <summary> /// 加载视图前执行 /// </summary> /// <param name="filterContext"></param> public void OnActionExecuting(ActionExecutingContext filterContext) { var Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType; var action = GetMethodInfoOrNull(filterContext.ActionDescriptor).Name; var Parameters = ConvertArgumentsToJson(filterContext.ActionParameters); logger.Info($"\r\n控制器:{Controller}\r\n方法:{action}\r\n参数:{Parameters}\r\nIP:{GetIP()}" + "\r\n"); //throw new NotImplementedException(); } public static MethodInfo GetMethodInfoOrNull(ActionDescriptor actionDescriptor) { if (actionDescriptor is ReflectedActionDescriptor) { return (actionDescriptor as ReflectedActionDescriptor).MethodInfo; } if (actionDescriptor is ReflectedAsyncActionDescriptor) { return (actionDescriptor as ReflectedAsyncActionDescriptor).MethodInfo; } if (actionDescriptor is TaskAsyncActionDescriptor) { return (actionDescriptor as TaskAsyncActionDescriptor).MethodInfo; } return null; } private string ConvertArgumentsToJson(IDictionary<string, object> arguments) { try { if (arguments.Count <= 0) { return "{}"; } var dictionary = new Dictionary<string, object>(); foreach (var argument in arguments) { dictionary[argument.Key] = argument.Value; } return Serialize(dictionary); } catch (Exception ex) { return "{}"; } } public string Serialize(object obj) { return JsonConvert.SerializeObject(obj); } /// <summary> /// 获取IP /// </summary> /// <returns></returns> private string GetIP() { string ip = string.Empty; if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"])) ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]); if (string.IsNullOrEmpty(ip)) ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]); return ip; } }
原文:https://www.cnblogs.com/wangyinlon/p/11445587.html