20

我正在尝试为[LoggedApiCall]a 创建一个过滤器Get()根据ApiController 这个:ASP.NET Web API ActionFilter 示例

我创建了一个System.Web.HttpFilters.ActionFilterAttribute. 覆盖允许OnActionExecuted(HttpActionExecutedContext actionExecutedContext)

我似乎找不到从HttpActionExecutedContext

也许我打算以错误的方式记录每个 API 调用?

4

1 回答 1

13

我们使用添加到的以下过滤器HttpConfiguration.Filters。一些代码:

internal class LoggingFilter : IExceptionFilter, IActionFilter
{
    private readonly ILog log;

    public LoggingFilter(ILog log)
    {
        if (log == null)
        {
            throw new ArgumentNullException("log");
        }

        this.log = log;
    }

    public bool AllowMultiple
    {
        get { return false; }
    }

    Task IExceptionFilter.ExecuteExceptionFilterAsync(HttpActionExecutedContext actionContext, CancellationToken cancellationToken)
    {
        if (actionContext == null)
        {
            throw new ArgumentNullException("actionContext");
        }

        this.log.Error(string.Format("Unexpected error while executing {0}", this.BuildLogEntry(actionContext.ActionContext)), actionContext.Exception);
        return TaskHelpers.Completed();
    }

    Task<HttpResponseMessage> IActionFilter.ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
    {
        if (actionContext == null)
        {
            throw new ArgumentNullException("actionContext");
        }

        if (continuation == null)
        {
            throw new ArgumentNullException("continuation");
        }

        if (!this.log.IsDebugEnabled)
        {
            // no point running at all if logging isn't currently enabled
            return continuation();
        }

        string logEntry = this.BuildLogEntry(actionContext);
        IDisposable logContext = this.log.DebugTiming("Executing {0}", logEntry);

        Task<string> requestContent;
        if (actionContext.Request.Content != null)
        {
            requestContent = actionContext.Request.Content.ReadAsStringAsync().ContinueWith(requestResult => string.IsNullOrEmpty(requestResult.Result) ? "N/A" : requestResult.Result);
        }
        else
        {
            requestContent = TaskHelpers.FromResult("N/A");
        }

        return requestContent.ContinueWith(
            requestResult =>
                {
                    this.log.DebugFormat("{0}, Request = {1}", logEntry, requestResult.Result);

                    return continuation()
                        .ContinueWith(t =>
                            {
                                Task<string> responseContent;
                                if (t.IsCompleted && t.Result.Content != null)
                                {
                                    responseContent = t.Result.Content.ReadAsStringAsync().ContinueWith(responseResult => string.IsNullOrEmpty(responseResult.Result) ? "N/A" : responseResult.Result);
                                }
                                else
                                {
                                    responseContent = TaskHelpers.FromResult("N/A");
                                }

                                return responseContent.ContinueWith(
                                    responseResult =>
                                        {
                                            using (logContext)
                                            {
                                                this.log.DebugFormat("{0}, Status Code: {1}, Response = {2}", logEntry, t.Result.StatusCode, responseResult.Result);
                                            }

                                            return t.Result;
                                        });
                            }).Unwrap();
                }).Unwrap();
    }

    /// <summary>
    /// Builds log data about the request.
    /// </summary>
    /// <param name="actionContext">Data associated with the call</param>
    private string BuildLogEntry(HttpActionContext actionContext)
    {
        string route = actionContext.Request.GetRouteData().Route.RouteTemplate;
        string method = actionContext.Request.Method.Method;
        string url = actionContext.Request.RequestUri.AbsoluteUri;
        string controllerName = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        string actionName = actionContext.ActionDescriptor.ActionName;

        return string.Format("{0} {1}, route: {2}, controller:{3}, action:{4}", method, url, route, controllerName, actionName);
    }
}

我们使用 log4net,您可以用ILog您认为合适的任何方式替换实现。ILog.DebugTiming只是一种扩展方法,它使用秒表来获取每个呼叫的经过时间。

编辑:这篇获取远程主机的 IP 地址的帖子详细介绍了如何获取远程调用者的 IP 地址。

干杯,院长

于 2012-07-10T19:59:42.243 回答