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("测试异常信息");
    }
    
  • 相关阅读:
    不同操作系统的宏定义区分
    WINDOWS下VS编译opencv并加载自定义模块
    基于模板匹配的马赛克检验
    [转]C++模板详解
    [Linux命令]Unix/Linux信号量的使用
    [C/C++基础]读写文件
    [Linux命令]查看Linux系统相关命令
    【Linux命令】查找命令
    【QT相关】文件、目录基础操作
    【MFC相关】图片显示
  • 原文地址:https://www.cnblogs.com/guxingy/p/12921966.html
Copyright © 2011-2022 走看看