WebAPI 操作返回

定义了一个返回枚举:

    public enum ResultExceptionEnum
    {
        积分不足       = 4002,
        支付失败       = 4003,
        用户不存在     = 4004,
        验证码发送失败 = 4005,
        验证码不正确   = 4006,
        账号已存在     = 4007,
        昵称已存在     = 4008,

        公会不存在     = 4100,
        公会名称已存在 = 4101,
        用户不在此公会 = 4102,

        社区不存在     = 4200,
        社区名称已存在 = 4201,
    }

 

定义一个返回 Exception

    public class ResultException : Exception
    {
        public ResultException(){}

        public ResultException(int code, string msg)
        {
            Code = code;
            Msg = msg;
        }

        public ResultException(ResultExceptionEnum code)
        {
            Code = code.GetHashCode();
            Msg = Enum.GetName(typeof(ResultExceptionEnum), code);
        }

        public int Code { get; set; }

        public string Msg { get; set; }

        public override string ToString()
        {
            return JsonConvert.SerializeObject(new { code = Code, msg = Msg });
        }

        public object ToResult()
        {
            var obj = new { code = Code, msg = Msg };
            return obj;
        }
    }

 

 

删除操作返回:

        // DELETE: api/Values/5
        public IHttpActionResult Delete(int id)
        {

            try
            {
                throw new ResultException(ResultExceptionEnum.验证码不正确);
            }
            catch (ResultException ex)
            {
                return Ok(ex.ToResult());
            }
            //return Ok(new { code = 200, msg = "删除成功" });
        }

 

上面两个风格,

1.  抛出异常,返回。

2. 直接返回

 

结果:

 

再来个异常版:

        // DELETE: api/Values/5
        public IHttpActionResult Delete(int id)
        {
            //try
            //{
            //    throw new ResultException(ResultExceptionEnum.验证码不正确);
            //}
            //catch (ResultException ex)
            //{
            //    return Ok(ex.ToResult());
            //}
            //return Ok(new { code = 200, msg = "删除成功" });

            throw new ResultException(ResultExceptionEnum.验证码不正确);
        }

 

配置下:

WebApiConfig

config.Filters.Add(new WebApiExceptionFilter());

    /// <summary>
    /// 全局API异常
    /// </summary>
    public class WebApiExceptionFilter : ExceptionFilterAttribute
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(HttpActionExecutedContext context)
        {
            var ex = context.Exception;
            if(ex is ResultException)
            {
                var ex2 = (ResultException)ex;
                context.Response = context.Request.CreateResponse(ex2.ToResult());
            }
            base.OnException(context);
        }
    }

 

只是这样抛异常 对性能有影响吗?

posted @ 2016-05-03 11:39 强悍的抽屉 阅读(...) 评论(...) 编辑 收藏