ASP.NET Web Api 2 - 记录特定操作的每个传入请求

时间:2016-01-15 21:04:18

标签: asp.net asp.net-web-api asp.net-web-api2

我正在使用ASP.NET Web Api 2.我编写了两个Filter Attributes来检查每个特定标头的传入请求,如果标头密钥不存在,则会向用户返回Unauthorized响应。

这就是我正在做的事情(其中一个过滤器):

public class HeaderFilterAttribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var req = actionContext.Request;


            if (! req.Headers.Contains("api-key") || req.Headers.GetValues("api-key") == null)
            {
                actionContext.Response = req.CreateResponse(HttpStatusCode.Unauthorized);
                actionContext.Response.Content = new StringContent("Token required", Encoding.UTF8, "text/html");
            }
        }
}

现在,如果请求包含有效的标头密钥,并且它们已到达正确的操作方法或端点,我想记录有关请求的某些详细信息。

为此方案创建过滤器属性的正确方法是什么?此过滤器属性将覆盖哪种方法?或者我可以在不创建过滤器属性的情况下实现所需的结果。我认为覆盖OnAuthorization()

是没有意义的

1 个答案:

答案 0 :(得分:1)

制作一个新的过滤器ActionFilterAttribute。您的授权过滤器将始终先运行,然后日志记录过滤器会记录您接受的请求。

public class MyLogFilterAttribute : ActionFilterAttribute
{
    public override OnActionExecuting(HttpActionContext actionContext)
    {
        // log info

        base.OnActionExecuting(actionContext);
    }
}

添加到基本控制器类以记录所有操作。

[HeaderFilter]
[MyLogFilter]
public abstract class BaseApiController : ApiController
{
}

public class MyApiController : BaseApiController
{
}