您现在的位置是:首页 > 伤感句子

Asp.net webApi统一封装返回结果+全局异常处理

作者:淼淼时间:2024-05-12 10:08:35分类:伤感句子

简介  文章浏览阅读810次,点赞7次,收藏9次。// 返回类型/// 状态代码/// 返回的数据/// 错误消息/// 是否成功String str;if (obj is String || obj is Char)//如果是字符串或字符直接返回else//否则序列

点击全文阅读

1.定义统一的返回类

/// <summary>    /// 返回类型    /// </summary>    public class ApiResultModel    {        private HttpStatusCode statusCode;        private object data;        private string errorMessage;        private bool isSuccess;        /// <summary>        /// 状态代码        /// </summary>        public HttpStatusCode StatusCode        {            get { return statusCode; }            set { statusCode = value; }        }        /// <summary>        /// 返回的数据        /// </summary>        public object Data        {            get { return data; }            set { data = value; }        }        /// <summary>        /// 错误消息        /// </summary>        public string ErrorMessage        {            get { return errorMessage; }            set { errorMessage = value; }        }        /// <summary>        /// 是否成功        /// </summary>        public bool IsSuccess        {            get { return isSuccess; }            set { isSuccess = value; }        }    }

2.定义不需要被封装的特性

public class NoPackageResult : Attribute{     }

3.定义Json结果处理类

public class JsonHelper    {        public static HttpResponseMessage toJson(Object obj)        {            String str;            if (obj is String || obj is Char)//如果是字符串或字符直接返回            {                str = obj.ToString();            }            else//否则序列为json字串            {                JavaScriptSerializer serializer = new JavaScriptSerializer();                str = serializer.Serialize(obj);            }            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };            return result;        }    }

4.定义统一格式过滤器

public class ApiResultAttribute : System.Web.Http.Filters.ActionFilterAttribute    {        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)        {            // 不包裹返回值            var noPackage = actionExecutedContext.ActionContext.ActionDescriptor.GetCustomAttributes<NoPackageResult>();            if (!noPackage.Any())            {                ApiResultModel result = new ApiResultModel();                //先捕获API内部的异常,无论代码能否完整执行,客户端都能得到正确的响应格式                if (actionExecutedContext.Exception != null)                {                    throw actionExecutedContext.Exception;                    //result.StatusCode = System.Net.HttpStatusCode.InternalServerError;                    //result.IsSuccess = false;                    //result.ErrorMessage = actionExecutedContext.Exception.Message;                }                else                {                    // 取得由 API 返回的状态代码                    result.StatusCode = actionExecutedContext.ActionContext.Response.StatusCode;                    var a = actionExecutedContext.ActionContext.Response.Content.ReadAsAsync<object>();                    if (!a.IsFaulted)                    {                        // 取得由 API 返回的资料                        result.Data = actionExecutedContext.ActionContext.Response.Content.ReadAsAsync<object>().Result;                    }                    //请求是否成功                    result.IsSuccess = actionExecutedContext.ActionContext.Response.IsSuccessStatusCode;                }                //结果转为自定义消息格式                HttpResponseMessage httpResponseMessage = JsonHelper.toJson(result);                // 重新封装回传格式                 actionExecutedContext.Response = httpResponseMessage;            }        }    }

5.在WebApiConfig下注册的结果过滤器

config.Filters.Add(new ApiResultAttribute());//重新包装结果

6.封装全局异常处理

/// <summary>    /// 全局异常过滤器     /// </summary>    /// <!-- 2019-8-22 16:18:10   添加 -->    public class ExceptionFilter : System.Web.Http.Filters.IExceptionFilter    {        public bool AllowMultiple => true;        public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)        {            var ex = actionExecutedContext.Exception.InnerException ?? actionExecutedContext.Exception;            return Task.Run(() =>            {                //异常记录日志到本地 2019-8-28 13:55:45 添加                //Common.LogHelpter.AddLog(ex.ToString());                string msg = ex.Message;                ApiResultModel result = new ApiResultModel();                result.IsSuccess = false;                result.StatusCode = System.Net.HttpStatusCode.OK;                result.ErrorMessage = msg;                //结果转为自定义消息格式                HttpResponseMessage httpResponseMessage = JsonHelper.toJson(result);                // 重新封装回传格式                 actionExecutedContext.Response = httpResponseMessage;            });        }    }

7.在WebApiConfig下注册的全局异常过滤器

config.Filters.Add(new ExceptionFilter());//重新包装异常处理过滤器

点击全文阅读

郑重声明:

本站所有活动均为互联网所得,如有侵权请联系本站删除处理

我来说两句