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之前处理。

上一篇:Oracle和MSSQL查询有多少张表


下一篇:es6 Object.assign ECMAScript 6 笔记(六) ECMAScript 6 笔记(一) react入门——慕课网笔记 jquery中动态新增的元素节点无法触发事件解决办法 响应式图像 弹窗细节 微信浏览器——返回操作 Float 的那些事 Flex布局 HTML5 data-* 自定义属性 参数传递的四种形式