zoukankan      html  css  js  c++  java
  • WebApi自定义全局异常过滤器及返回数据格式化

        WebApi在这里就不多说了,一种轻量级的服务,应用非常广泛。我这这里主要记录下有关 WebApi的相关知识,以便日后使用。

        当WebApi应用程序出现异常时,我们都会使用到异常过滤器进行日志记录,并在Global全局文件中注册,过滤器是一种AOP设计思想,即面向切面编程,其跟主业务无关,可以减少项目中的代码量以及降低各模块之间的耦合度。首先是ExceptionFilterAttribute抽象类,重写其中的OnException方法去自定义自己的异常过滤器。直接上代码。

    /// <summary>
        /// 自定义程序异常过滤器
        /// </summary>
        public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
        {
            /// <summary>
            /// NLog日志记录
            /// </summary>
            private static Logger logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);
    
    
            /// <summary>
            /// 异常处理
            /// </summary>
            /// <param name="context"></param>
            public override void OnException(HttpActionExecutedContext context)
            {
    
                var ex = context.Exception.InnerException == null ? context.Exception : context.Exception.InnerException;
                //记录日志错误信息
                logger.Error($"{context.ActionContext.ControllerContext.ControllerDescriptor.ControllerType.FullName}." +
                    $"{context.ActionContext.ActionDescriptor.ActionName}{Environment.NewLine}" +
                    $"Arguments: {JsonConvert.SerializeObject(context.ActionContext.ActionArguments)}{Environment.NewLine}" +
                    $"Message:{ex.ToString()}{Environment.NewLine}");
                //返回客户端异常信息
                context.Response = context.Request.CreateResponse(HttpStatusCode.OK,new WebApiFitlerResult() {
                    code = WebApiFitlerResult.CodeEnumType.程序异常,
                    msg = ex.Message
                });
            }
        }
    View Code

       其中WebApiFitlerResult类为博主自定的错误信息类,包含错误状态码和错误信息属性。 

       最后在Global文件中的Application_Start管道方法中的全局配置中注册。代码如下。(此代码包含返回数据格式化设置和跨域设置)

     protected void Application_Start()
            {
    //移除xml返回格式 GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat; json.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
    //返回空值设置 json.SerializerSettings.NullValueHandling
    = Newtonsoft.Json.NullValueHandling.Ignore; json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.None json.SerializerSettings.ContractResolver = new DefaultContractResolver(); //全局注册 GlobalConfiguration.Configure(x=> { //跨域 x.EnableCors(new EnableCorsAttribute("*", "*", "*")); //异常过滤器注册 x.Filters.Add(new CustomExceptionFilterAttribute());
    //webapi路由注册 x.MapHttpAttributeRoutes(); }); }

     我这边WebApi项目中返回的数据只有json格式,所以就把xml返回格式删除了。

      

  • 相关阅读:
    python中以带mixin命名的类有什么特点?
    php使用redis做缓存和使用redis保存session
    python连接hive数据库count查询慢的解决办法
    内网环境数据库查看工具使用笔记支持hive edismysql
    深入mysql的视图复习笔记
    Laravel 整合IOS苹果授权登录(JWT验证模式)
    PHP 读取PDF文件内容之PdfParser
    git发生冲突:error: Your local changes to the following files would be overwritten by merge
    PHP 创建GUID唯一标识
    Laravel 模型关联、关联查询、预加载使用实例
  • 原文地址:https://www.cnblogs.com/xiongtaotao/p/11598059.html
Copyright © 2011-2022 走看看