如果每个API都写异常处理逻辑,只需要在需要捕

作者: 编程  发布:2019-11-21

扬言:本代码只适用于.NET MVC.

概述: 

  ASP.NET Web API 的好用利用过的都驾驭,未有复杂的布局文件,三个轻巧易行的ApiController加上须要的Action就能够做事。不过项目,总有这几个发生,本节就来谈谈API的不胜的联结管理和写统生龙活虎写log逻辑的消除方案。

先创建一个类世襲ActionFilterAttribute那几个抽象类以致贯彻IExceptionFilter接口,并促成它的方法OnException。

问题:

   在ASP.NET Web API编写时,假设各类API都写非凡管理逻辑,不但加大了支付专业量,且每种开拓职员管理特别再次回到的数据结构也不尽相似,在充裕产生情形下,客户端管理极其的逻辑就不再通用,也还要加大了对接接口职员的职业量,好的API错误码和错误消息都以固定格式,并后台应该有对应的不行记录。

代码如下:

可怜的联合管理的得以完成:

1. 先是定义十三分管理Attribute,世袭System.Web.Http.Filters.ExceptionAttribute, 重写OnException, 代码如下

图片 1图片 2

 1   public class ErrorHandleAttribute : System.Web.Http.Filters.ExceptionFilterAttribute
 2     {
 3         private string _msg = string.Empty;
 4 
 5         public ErrorHandleAttribute() { }
 6 
 7         public ErrorHandleAttribute(string msg)
 8         {
 9             this._msg = msg;
10         }
11         public override void OnException(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
12         {
13             base.OnException(actionExecutedContext);
14             // 取得发生异常时的错误讯息
15             //var errorMessage = actionExecutedContext.Exception.Message;
16             // 标记log
17             var logAction = actionExecutedContext.ActionContext.ActionDescriptor.GetCustomAttributes<NoErrorHandlerAttribute>();
18             if (logAction.Any())
19             {
20                 actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError, new ResultData(ResultType.SystemException, actionExecutedContext.Exception.Message));
21                 return;
22             }
23 
24             var request = HttpContext.Current.Request;
25             var logDetail = new LogDetail
26             {
27                 //获取action名称
28                 ActionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
29                 //获取Controller 名称
30                 ControllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName,
31                 Navigator = request.UserAgent,
32                 //获取访问的ip
33                 IP = request.UserHostAddress,
34                 UserHostName = request.UserHostName,
35                 UrlReferrer = request.UrlReferrer != null ? request.UrlReferrer.AbsoluteUri : "",
36                 Browser = request.Browser.Browser + " - " + request.Browser.Version + " - " + request.Browser.Type,
37                 //获取request提交的参数
38                 Paramaters = GetRequestValues(actionExecutedContext),
39                 //获取response响应的结果
40                 //ExecuteResult = GetResponseValues(actionExecutedContext),  //这句会报错,异常没有处理结果
41                 AttrTitle = this._msg,
42                 ErrorMsg = string.Format("错误信息:{0}, 异常跟踪:{1}", actionExecutedContext.Exception.Message, actionExecutedContext.Exception.StackTrace),
43                 RequestUri = request.Url.AbsoluteUri
44             };
45 
46             // 写log
47             var logRep = ContainerManager.Resolve<ISysLogRepository>();
48             var log = new Log()
49             {
50                 Action = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName + "/" + actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
51                 CreateDate = DateTime.Now,
52                 CreatorLoginName = RISContext.Current.CurrentUserInfo.UserName,
53                 IpAddress = request.UserHostAddress,
54                 Detail = Utility.JsonSerialize<LogDetail>(logDetail)
55             };
56 
57             logRep.Add(log);
58             actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError, new ResultData(ResultType.SystemException, actionExecutedContext.Exception.Message));
59         }
60         
61         /// <summary>
62         /// 读取request 的提交内容
63         /// </summary>
64         /// <param name="actionExecutedContext"></param>
65         /// <returns></returns>
66         public string GetRequestValues(HttpActionExecutedContext actionExecutedContext)
67         {
68 
69             Stream stream = actionExecutedContext.Request.Content.ReadAsStreamAsync().Result;
70             Encoding encoding = Encoding.UTF8;
71             /*
72                 这个StreamReader不能关闭,也不能dispose, 关了就傻逼了
73                 因为你关掉后,后面的管道  或拦截器就没办法读取了
74             */
75             var reader = new StreamReader(stream, encoding);
76             string result = reader.ReadToEnd();
77             /*
78             这里也要注意:   stream.Position = 0;
79             当你读取完之后必须把stream的位置设为开始
80             因为request和response读取完以后Position到最后一个位置,交给下一个方法处理的时候就会读不到内容了。
81             */
82             stream.Position = 0;
83             return result;
84         }
85     }

View Code

  1. 接下去定义无需卓殊管理的Attribute,代码如下:

    1 [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true)] 2 public class NoErrorHandlerAttribute : Attribute 3 { 4 }

  2. 在HttpConfiguration中登记使用 ErrorHandleAttribute, 注册代码如下:

  config.Filters.Add(new ErrorHandleAttribute("错误管理"));

  通常在等级次序的WebApiConfig.cs中注册此属性:

 1  /// <summary>
 2     /// WebApiConfig
 3     /// </summary>
 4     public static class WebApiConfig
 5     {
 6         /// <summary>
 7         /// WebApiConfig Register
 8         /// </summary>
 9         /// <param name="config"></param>
10         public static void Register(HttpConfiguration config)
11         {
12             //config.Filters.Add(new TokenAuthorizeAttribute());
13             config.MessageHandlers.Add(new CrosHandler());
14             config.Filters.Add(new ApiAuthorizeAttribute());
15             config.Filters.Add(new ErrorHandleAttribute("错误处理"));
16             // Web API 路由
17             config.Routes.MapHttpRoute(
18                 name: "DefaultApi",
19                 routeTemplate: "mobileapi/{controller}/{action}/{id}",
20                 defaults: new { controller = "Test", action = "GetTestValue", id = RouteParameter.Optional }
21             );
22         }
23     }

如此那般就足以了,在各种Action中就无须写try catch了,不然不试行ErrorHandle中丰裕管理逻辑
4. 若是特别规的Controller或许Action不需求纪录和管理特别,能够在Controller或然Action上加多[NoErrorHandler],那样就不会推行ErrorHandle中充裕管理逻辑

以上部分是那多少个的统生龙活虎管理逻辑, 接下来落到实处统生机勃勃写Log的 Attribute作用

using FrameWork.Common;
using System.Web;
using System.Web.Mvc;

namespace FrameWork.Web
{
    public class ErrorHandleAttribute : ActionFilterAttribute, IExceptionFilter
    {
        /// <summary>
        /// 异常
        /// </summary>
        public void OnException(ExceptionContext filterContext)
        {
            //获取异常信息,入库保存
            var error = filterContext.Exception;
            var message = error.Message;//错误信息
            var url = HttpContext.Current.Request.RawUrl;//错误发生地址
            var controllerName = filterContext.RouteData.Values["controller"].ToString();
            var actionName = filterContext.RouteData.Values["action"].ToString();
            var exception = filterContext.Exception.ToString();

            Log4NetHelp.Error("出错位置:" + url, filterContext.Exception);
            filterContext.HttpContext.Response.Redirect("/Account/Login");//否则跳转至登陆页
        }
    }
}

集结写Log的 Attribute功用实现:

 1. 首先定义写Log的Attribute,世襲System.Web.Http.Filters.ActionFilterAttribute,重写OnActionExecuting和OnActionExecuted,代码如下:

图片 3图片 4

  1  public class LogAttribute : ActionFilterAttribute
  2     {
  3         private string _msg = string.Empty;
  4         private string _token = string.Empty;
  5         private string _remark = string.Empty;
  6         public LogAttribute() { }
  7 
  8         public LogAttribute(string msg)
  9         {
 10             this._msg = msg;
 11         }
 12 
 13         //http://www.cnblogs.com/shan333chao/p/5002054.html
 14         private static readonly string key = "enterTime";
 15         private const string UserToken = "token";
 16         public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
 17         {
 18             if (actionContext.Request.Method != HttpMethod.Options)
 19             {
 20                 // 标记log
 21                 var logAction = actionContext.ActionDescriptor.GetCustomAttributes<NoLogAttribute>();
 22                 if (!logAction.Any())
 23                 {
 24                     actionContext.Request.Properties[key] = DateTime.Now.ToBinary();
 25                     this._token = GetToken(actionContext, out this._remark);
 26                 }
 27             }
 28             base.OnActionExecuting(actionContext);
 29         }
 30 
 31         public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 32         {
 33             if (actionExecutedContext.Request.Method != HttpMethod.Options)
 34             {
 35                 object beginTime = null;
 36                 if (actionExecutedContext.Request.Properties.TryGetValue(key, out beginTime))
 37                 {
 38                     DateTime time = DateTime.FromBinary(Convert.ToInt64(beginTime));
 39                     var request = HttpContext.Current.Request;
 40                     var logDetail = new LogDetail
 41                     {
 42                         //获取action名称
 43                         ActionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
 44                         //获取Controller 名称
 45                         ControllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName,
 46                         //获取action开始执行的时间
 47                         EnterTime = time,
 48                         //获取执行action的耗时
 49                         CostTime = (DateTime.Now - time).TotalMilliseconds,
 50                         Navigator = request.UserAgent,
 51                         Token = this._token,
 52                         //获取用户ID
 53                         UId = UserTokenManager.GetUId(this._token),
 54                         //获取访问的ip
 55                         IP = request.UserHostAddress,
 56                         UserHostName = request.UserHostName,
 57                         UrlReferrer = request.UrlReferrer != null ? request.UrlReferrer.AbsoluteUri : "",
 58                         Browser = request.Browser.Browser + " - " + request.Browser.Version + " - " + request.Browser.Type,
 59                         //获取request提交的参数
 60                         Paramaters = GetRequestValues(actionExecutedContext),
 61                         //获取response响应的结果
 62                         ExecuteResult = GetResponseValues(actionExecutedContext),
 63                         AttrTitle = this._msg,
 64                         Remark = this._remark,
 65                         RequestUri = request.Url.AbsoluteUri
 66                     };
 67 
 68                     // 登录log
 69                     var logRep = ContainerManager.Resolve<ISysLogRepository>();
 70                     var log = new Log()
 71                     {
 72                         Action = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName + "/" + actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
 73                         CreateDate = DateTime.Now,
 74                         CreatorLoginName = RISContext.Current.CurrentUserInfo.UserName,
 75                         IpAddress = request.UserHostAddress,
 76                         Detail = Utility.JsonSerialize<LogDetail>(logDetail)
 77                     };
 78 
 79                     logRep.Add(log);
 80                 }
 81             }
 82 
 83             base.OnActionExecuted(actionExecutedContext);
 84         }
 85 
 86         private string GetToken(System.Web.Http.Controllers.HttpActionContext actionContext, out string msg)
 87         {
 88             Dictionary<string, object> actionArguments = actionContext.ActionArguments;
 89             HttpMethod type = actionContext.Request.Method;
 90             msg = "";
 91             var token = "";
 92             if (type == HttpMethod.Post)
 93             {
 94                 if (actionArguments.ContainsKey(UserToken))
 95                 {
 96                     if (actionArguments[UserToken] != null)
 97                         token = actionArguments[UserToken].ToString();
 98                 }
 99                 else
100                 {
101                     foreach (var value in actionArguments.Values)
102                     {
103                         if (value != null && value.GetType().GetProperty(UserToken) != null)
104                             token = value.GetType().GetProperty(UserToken).GetValue(value, null).ToString();
105                     }
106                 }
107 
108                 if (string.IsNullOrEmpty(token))
109                     msg = "匿名用户";
110             }
111             else if (type == HttpMethod.Get)
112             {
113                 if (!actionArguments.ContainsKey(UserToken))
114                     msg = "匿名用户";
115                 // throw new HttpException(401, "还未登录");
116 
117                 if (actionArguments[UserToken] != null)
118                     token = actionArguments[UserToken].ToString();
119                 else
120                     msg = "匿名用户";
121             }
122             else if (type == HttpMethod.Options)
123             {
124 
125             }
126             else
127             {
128                 throw new HttpException(404, "暂未开放除POST,GET之外的访问方式!");
129             }
130             return token;
131         }
132         /// <summary>
133         /// 读取request 的提交内容
134         /// </summary>
135         /// <param name="actionExecutedContext"></param>
136         /// <returns></returns>
137         public string GetRequestValues(HttpActionExecutedContext actionExecutedContext)
138         {
139 
140             Stream stream = actionExecutedContext.Request.Content.ReadAsStreamAsync().Result;
141             Encoding encoding = Encoding.UTF8;
142             /*
143                 这个StreamReader不能关闭,也不能dispose, 关了就傻逼了
144                 因为你关掉后,后面的管道  或拦截器就没办法读取了
145             */
146             var reader = new StreamReader(stream, encoding);
147             string result = reader.ReadToEnd();
148             /*
149             这里也要注意:   stream.Position = 0;
150             当你读取完之后必须把stream的位置设为开始
151             因为request和response读取完以后Position到最后一个位置,交给下一个方法处理的时候就会读不到内容了。
152             */
153             stream.Position = 0;
154             return result;
155         }
156 
157         /// <summary>
158         /// 读取action返回的result
159         /// </summary>
160         /// <param name="actionExecutedContext"></param>
161         /// <returns></returns>
162         public string GetResponseValues(HttpActionExecutedContext actionExecutedContext)
163         {
164             Stream stream = actionExecutedContext.Response.Content.ReadAsStreamAsync().Result;
165             Encoding encoding = Encoding.UTF8;
166             /*
167             这个StreamReader不能关闭,也不能dispose, 关了就傻逼了
168             因为你关掉后,后面的管道  或拦截器就没办法读取了
169             */
170             var reader = new StreamReader(stream, encoding);
171             string result = reader.ReadToEnd();
172             /*
173             这里也要注意:   stream.Position = 0; 
174             当你读取完之后必须把stream的位置设为开始
175             因为request和response读取完以后Position到最后一个位置,交给下一个方法处理的时候就会读不到内容了。
176             */
177             stream.Position = 0;
178             return result;
179         }
180     }

View Code

  1. 接下去定义不须要记录log的Attribute,代码如下:

    1 [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true)] 2 public class NoErrorHandlerAttribute : Attribute 3 { 4 }

  2. 介意不要在HttpConfiguration中注册使用 LogAttribute,除非你想具有的乞请都写log,在不须要写log的Action上增多[NoLog],不然只需求在要求记录log的Action增添[Log]就能够完结写log的成效。

此篇到此结束,绝相比较轻松,应接大家谈谈!

 

怎么运用啊?

只必要在急需捕捉十分的调控器加上[ErrorHandle]即可。

例如:

    [ErrorHandle]
    public abstract class AdminControllerBase : Controller
    {
          //代码逻辑
    }

比如持续AdminControllerBase恐怕隐含[ErrorHandle]个性的类和情势现身了不当,都会举办OnException方法,

接下来写上团结的不行管理逻辑就可以。

 

本文由9159.com发布于编程,转载请注明出处:如果每个API都写异常处理逻辑,只需要在需要捕

关键词:

上一篇:没有了
下一篇:没有了