webapi记录请求和返回日志

阅读更多
需求:
记录每个接口的请求参数及返回参数,方便以后回溯

filter的介绍
filter在Web API中经常会用到,主要用于记录日志,安全验证,全局错误处理等;Web API提供两种过滤器的基本类型:actionfilterattribute,exceptionfilterattribute;两个类都是抽象类,actionfilter主要实现执行请求方法体之前(覆盖基类方法OnActionExecuting),和之后的事件处理(覆盖基类方法OnActionExecuted);exceptionfilter主要实现触发异常方法(覆盖基类方法OnException)。

下来就是写个信的filter来扑捉请求的和返回的信息,如下代码:
public class WebApiActionDebugFilter : System.Web.Http.Filters.ActionFilterAttribute  
    {  
        ///   
        /// 是否开启调试  
        ///   
        private bool _isDebugLog = true;  
  
        public string DebugId  
        {  
            set  
            {  
                var session = System.Web.HttpContext.Current.Session;  
                if (session != null)  
                {  
                    session["RequestDebugId"] = value;  
                }  
            }  
            get  
            {  
                var session = System.Web.HttpContext.Current.Session;  
                if (session != null && session["RequestDebugId"]!=null)  
                {  
                    return session["RequestDebugId"].ToString();  
                }  
                return string.Empty;  
            }  
        }  
  
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext context)  
        {  
            base.OnActionExecuting(context);  
            //记录请求内容  
            if (_isDebugLog)  
            {  
                try  
                {  
                    var guid = System.Guid.NewGuid().ToString();  
                    DebugId = guid;  
                    var session = System.Web.HttpContext.Current.Session;  
                    var request = System.Web.HttpContext.Current.Request;  
                    var keys = request.Form.AllKeys;  
                      
                    var task = context.Request.Content.ReadAsStreamAsync();  
                    var content = string.Empty;  
                    using (System.IO.Stream sm = task.Result)  
                    {  
                        if (sm != null)  
                        {  
                            sm.Seek(0, SeekOrigin.Begin);  
                            int len = (int) sm.Length;  
                            byte[] inputByts = new byte[len];  
                            sm.Read(inputByts, 0, len);  
                            sm.Close();  
                            content = Encoding.UTF8.GetString(inputByts);  
                        }  
                    }  
                    string pars = string.Format("请求:\r\n id = {3};\r\n sessionId = {0};\r\n url = {1};\r\n contentType = {4};\r\n content = {2};"  
                        ,""// (session==null)?"...":session.SessionID  
                        , request.RawUrl  
                        , content  
                        , guid  
                        , request.ContentType);  
  
                }  
                catch (Exception ex)  
                {  
                }  
            }  
        }  
        public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext context)  
        {  
            base.OnActionExecuted(context);  
            //记录请求内容  
            if (_isDebugLog)  
            {  
                try  
                {  
                    var session = System.Web.HttpContext.Current.Session;  
                    var task = context.Response.Content.ReadAsStringAsync();  
                    var txt = task.Result;  
                    string pars = string.Format("响应:\r\n id = {2};\r\n sessionId = {0};\r\n response = {1}"  
                        , ""//(session == null) ? "..." : session.SessionID  
                        , txt  
                        , DebugId);  
                }  
                catch (Exception ex)  
                {  
                }  
            }  
        }  
          
    }  



使用方式:
1、在每个方法添加此属性[WebApiActionDebugFilter]
2、在webapi的路由配置里增加
 config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "WebApi/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }

            );

            //注册
            config.Filters.Add(new WebApiActionDebugFilter());

可能出现的问题:


注册WebApiActionDebugFilter时将它写在了FilterConfig文件中
运行时出现的错误提示:
给定的筛选器实例必须实现以下一个或多个筛选器接口: System.Web.Mvc.IAuthorizationFilter、System.Web.Mvc.IActionFilter、System.We

原因:FilterConfig是给MVC使用的,api用的是webapiconfig


参考学习:
https://www.cnblogs.com/mychris/p/5157655.html
https://www.cnblogs.com/duanjt/p/6734372.html
http://blog.csdn.net/xxj_jing/article/details/48806829
https://www.cnblogs.com/shi-meng/p/4635571.html

你可能感兴趣的:(webapi记录请求和返回日志)