zoukankan      html  css  js  c++  java
  • 接口 web api 全局异常过滤器

    原文:https://www.cnblogs.com/mstmdev/p/5471099.html



    1、JsonMsg,统一返回消息的格式

    
    /// <summary>
    /// 返回消息
    /// </summary>
    public class JsonMsg<T> where T : class
    {
        /// <summary>
        /// 状态码 0:失败 1:成功
        /// </summary>
        public int code { get; set; }
    
        /// <summary>
        /// 消息
        /// </summary>
        public string msg { get; set; }
    
        /// <summary>
        /// 内容
        /// </summary>
        public T obj { get; set; }
    
        /// <summary>
        /// 图标
        /// </summary>
        public int icon { get; set; }
    
    
        public static JsonMsg<T> OK(T obj, string msg = "成功")
        {
            return new JsonMsg<T>() { code = 1, msg = msg, obj = obj, icon = 1 };
        }
    
        public static JsonMsg<T> Error(T obj, string msg = "失败")
        {
            return new JsonMsg<T>() { code = 0, msg = msg, obj = obj, icon = 1 };
        }
    }
    

    2、WebApiExceptionFilterAttribute,自定义异常过滤器

    public class WebApiExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnException(actionExecutedContext);
    
    
            var obj = JsonMsg<string>.Error(null, actionExecutedContext.Exception.Message);
    
            var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            response.Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
            actionExecutedContext.Response = response;
        }
    }
    

    3、Global,在Application_Start方法中,添加如下代码

    GlobalConfiguration.Configuration.Filters.Add(new WebApiExceptionFilterAttribute());

    4、HomeApiController,创建一个测试

    [AllowAnonymous]
    public void testEx()
    {
        throw new Exception("测试异常信息");
    }
    
  • 相关阅读:
    PostgreSQL恢复误操作
    PostgreSQL修改表空间
    vim技巧记录
    postgresql recovery.conf文件内容说明
    转一篇pgpool配置
    由PostgreSQL的区域与字符集说起(转)
    PostgreSQL老司机博客 经常翻翻收获不小
    两位数相乘的口算方法
    五线谱升调与降调
    js中的封装、继承、多态
  • 原文地址:https://www.cnblogs.com/guxingy/p/12921966.html
Copyright © 2011-2022 走看看