WebAPI 用户认证防篡改实现HMAC(三)异常信息处理 AbsCommonExceptionFilterAttribute

每个平台都应该具备异常处理策略,此处异常处理策略只针对用户请求产生的当前线程异常,不包括异步处理时产生的未捕获异常,关于异常处理建议大家可以去看下微软企业库的 Exception Handling Application Block

AbsCommonExceptionFilterAttribute,同信息验证一样,异常也是通过Attrbute来处理

    using System.Net;
    using System.Net.Http;
    using System.Web.Http.Filters;

    /// <summary>
    /// WebAPI异常响应处理
    /// </summary>
    public abstract class AbsCommonExceptionFilterAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// Raises the exception event
        /// </summary>
        /// <param name="actionExecutedContext">The context for the action.</param>
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            string exceptionStr = string.Empty;
            HttpStatusCode statusCode = HttpStatusCode.InternalServerError;
            if (this.AllowException)
            {//允许在返回结果中包含异常信息
                exceptionStr = this.HandleException(actionExecutedContext, ref statusCode);
            }
            //此处可以修正返回值
            actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(statusCode, new StringContent(exceptionStr));
            //actionExecutedContext.Response = new HttpResponseMessage(statusCode) { Content = new StringContent(exceptionStr) };
        }
        /// <summary>
        /// 是否允许返回异常信息,测试环境中应当允许返回异常以辅助测试,正式环境中应禁止返回异常
        /// </summary>
        protected abstract bool AllowException { get; }
        /// <summary>
        /// 异常处理策略
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        protected virtual string HandleException(HttpActionExecutedContext actionExecutedContext, ref HttpStatusCode statusCode)
        {
            //此处可以对异常进行分类处理,修正返回的HttpStatusCode
            //也可以对异常进行封装或者转换,建议采用微软企业库的Exception Handling Application Block
            //if (actionExecutedContext.Exception is NotImplementedException)
            //{
            //    statusCode = HttpStatusCode.NotImplemented;
            //}
            return actionExecutedContext.Exception.ToString();
        }
    }
子类例子
    public class CommonExceptionFilterAttribute : AbsCommonExceptionFilterAttribute
    {
        protected override bool AllowException
        {
            get { return true; }
        }
    }
注册Attribute,在默认生成的WebApiConfig文件的Register方法中增加如下代码
config.Filters.Add(new CommonExceptionFilterAttribute());

你可能感兴趣的:(C#,webapi)