.NET MVC获取请求参数输出到日志
方法
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; } }
作者:银龙
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!