Sharepoint初学者!

ASP.NET Web API之消息拦截

要在action执行前后做额外处理,那么ActionFilterAttribute和ApiControllerActionInvoker就派上用场了。比如客户端请求发过来的参数为用户令牌字符串token,我们要在action执行之前先将其转为action参数列表中对应的用户编号ID,如下:

public class TokenProjectorAttribute : ActionFilterAttribute
{
    private string _userid = "userid";
    public string UserID
    {
        get { return _userid; }
        set { _userid = value; }
    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ActionArguments.ContainsKey(UserID))
        {
            //参数列表中不存在userid,写入日志
            //……
            var response = new HttpResponseMessage();
            response.Content = new StringContent("用户信息转换异常.");
            response.StatusCode = HttpStatusCode.Conflict;
            //在这里为了不继续走流程,要throw出来,才会立马返回到客户端
            throw new HttpResponseException(response);
        }
        //userid系统赋值
        actionContext.ActionArguments[UserID] = actionContext.Request.Properties["shumi_userid"];
        base.OnActionExecuting(actionContext);
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        base.OnActionExecuted(actionExecutedContext);
    }
}

 

ActionFilterAttribute如何应用到action,和前面的ExceptionFilterAttribute类似。

ApiControllerActionInvoker以上述Exception为例:

public class ServerAPIControllerActionInvoker : ApiControllerActionInvoker
{
    public override Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        //对actionContext做一些预处理
        //……
        var result = base.InvokeActionAsync(actionContext, cancellationToken);
        if (result.Exception != null && result.Exception.GetBaseException() != null)
        {
            var baseException = result.Exception.GetBaseException();

            if (baseException is BusinessException)
            {
                return Task.Run<HttpResponseMessage>(() =>
                {
                    var response = new HttpResponseMessage(HttpStatusCode.ExpectationFailed);
                    BusinessException exception = (BusinessException)baseException;
                    response.Headers.Add("BusinessExceptionCode", exception.Code);
                    response.Headers.Add("BusinessExceptionMessage", exception.Message);
                    return response;
                });
            }
            else
            {
                return Task.Run<HttpResponseMessage>(() => new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
        }
        return result;
    }
}

 然后注册至GlobalConfiguration.Configuration.Services中。由于ApiControllerActionInvoker乃是影响全局的,所以若要对部分action进行包装处理,应该优先选择ActionFilterAttribute。另外ApiControllerActionInvoker在ActionFilterAttribute之前处理。

posted on 2017-04-12 14:02  Sharepoint初学者!  阅读(302)  评论(0编辑  收藏  举报