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("测试异常信息");
    }
    
  • 相关阅读:
    sqlserver数据导入导出问题
    关于数据库冗余设计的思考
    cordova插件开发注意事项
    阿里云旺集成问题
    aspnet webapi 跨域请求 405错误
    跨域无法获取自定义header的问题
    angular input标签只能单向传递数据的问题
    android audio无法自动播放
    jquery mobile 问问多多
    mysql 表表连接的问题。
  • 原文地址:https://www.cnblogs.com/guxingy/p/12921966.html
Copyright © 2011-2022 走看看