你的位置:首页 > ASP.net教程

[ASP.net教程]Web API 下的 ActionFilter 与 ExceptionFilter


本文重点会标红。
背景需求,在进入action之前做sign验证,以及反正错误时,记录log,返回错误的json形式信息。
#region 普通 ActionFilter add by caoheyang 20150319  /// <summary>  /// sign 以及参数合法性验证过滤器 add by caoheyang 20150318  /// </summary>  public class SignOpenApiAttribute : System.Web.Http.Filters.ActionFilterAttribute  {    /// <summary>    /// 重写OnActionExecuting方法  在进入控制器之前验证 sign以及 参数合法性信息 add by caoheyang 20150318    /// </summary>    /// <param name="actionContext"></param>    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)    {      lock (actionContext)      {        dynamic paramodel = actionContext.ActionArguments["paramodel"]; //当前请求的参数对象         if (actionContext.ModelState.Count > 0 || paramodel == null) //参数错误,请求中止          actionContext.Response = actionContext.ActionDescriptor.ResultConverter.Convert              (actionContext.ControllerContext, ResultModel<object>.Conclude(OrderApiStatusType.ParaError));        IGroupProvider groupProvider = new GroupProvider();        GroupApiConfigModel groupCofigInfo = groupProvider.GetGroupApiConfigByAppKey(paramodel.app_key, paramodel.v).Data;        if (groupCofigInfo != null && groupCofigInfo.IsValid == 1)//集团可用,且有appkey信息        {          string signStr = groupCofigInfo.AppSecret + "app_key=" + paramodel.app_key + "timestamp" + paramodel.timestamp + "v=" + paramodel.v + groupCofigInfo.AppSecret;          string sign = MD5.Encrypt(signStr);          paramodel.group = ParseHelper.ToInt(groupCofigInfo.GroupId, 0);          actionContext.ActionArguments["paramodel"] = paramodel; ;          if (sign != paramodel.sign)  //sign错误,请求中止            actionContext.Response = actionContext.ActionDescriptor.ResultConverter.Convert              (actionContext.ControllerContext, ResultModel<object>.Conclude(OrderApiStatusType.SignError)); //此处标红需要与 apicontroller里应用fillter的action返回值一直。        }        else          actionContext.Response = actionContext.ActionDescriptor.ResultConverter.Convert              (actionContext.ControllerContext, ResultModel<object>.Conclude(OrderApiStatusType.SignError)); //sign错误,请求中止      }    }  }  #endregion  #region ExceptionFilter add by caoheyang 20150319  /// <summary>  /// 自定义全局异常处理类 add by caoheyang 20150319  全局过滤器,记录log  /// </summary>  public class OpenApiHandleErrorAttribute : ExceptionFilterAttribute  {    /// <summary>    /// 重写异常处理方法 add by caoheyang 20150205 其次执行    /// </summary>    /// <param name="filterContext">上下文对象 该类继承于ControllerContext</param>    public override void OnException(HttpActionExecutedContext filterContext)    {      LogHelper.LogWriterFromFilter(filterContext.Exception);    }  }  /// <summary> action过滤器,当内部代码发生异常时,改变当前的请求服务器端返回信息  /// 自定义action异常处理类,捕获异常,返回系统错误提示信息 add by caoheyang 20150319  /// </summary>  public class OpenApiActionErrorAttribute : ExceptionFilterAttribute  {    /// <summary>    /// 重写异常处理方法 add by caoheyang 20150205  首先执行     /// </summary>    /// <param name="filterContext">上下文对象 该类继承于ControllerContext</param>    public override void OnException(HttpActionExecutedContext filterContext)    {      filterContext.Response = filterContext.ActionContext.ActionDescriptor.ResultConverter.       Convert(filterContext.ActionContext.ControllerContext, ResultModel<object>.Conclude(OrderApiStatusType.SystemError));
      //此处标红需要与 apicontroller里应用fillter的action返回值一直。
} } #endregion

ApiController eg。

 // POSR: Order GetStatus  paramodel 固定 必须是 paramodel    /// <summary>    /// 订单状态查询功能 add by caoheyang 20150316    /// </summary>    /// <returns></returns>    [HttpPost]    [SignOpenApi] //sign验证过滤器 设计参数验证,sign验证 add by caoheyang 201503167    [OpenApiActionError] //异常过滤器 add by caoheyang 一旦发生异常,客户端返回系统内部错误提示    public ResultModel<object> GetStatus(ParaModel<GetStatusPM_OpenApi> paramodel)    {         }