微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-mvc – 如何添加日志到MVC4 WebApi

我试图为ApiController上的Get()创建一个[LoggedApiCall]过滤器
据此: ASP.NET Web API ActionFilter example

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

我似乎找不到从HttpActionExecutedContext获取调用者的IP的方法

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

解决方法

我们使用我们添加到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}",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只是一种扩展方法,它使用秒表来获取每次调用的时间。

编辑:
这篇文章Get the IP address of the remote host具有如何获取远程调用者的IP地址的详细信息。

干杯,院长

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“WPF...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这...
Some samples are below for ASP.Net web form controls:(from http://www.visualize.uk.com/resources/asp
问题描述: 对于未定义为 System.String 的列,唯一有效的值是(引发异常)。 For columns not defined as System.String, the only vali
最近用到了CalendarExtender,结果不知道为什么发生了错位,如图在Google和百度上找了很久,中文的文章里面似乎只提到了如何本地化(就是显示中文的月份)以及怎么解决被下拉框挡住的问题,谈
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence changed a lot since 1.1. Here is the order: App
静态声明: &#39; Style=&quot;position: relative&quot; AppendDataBoundItems=&quot;True&quot;&gt; (无 或 空 或
以下内容是从网络上搜集资料,然后整理而来的。不当之处,请不吝指教。(The following were from network, and edited by myself. Thanks in a
Imports System Imports System.Reflection Namespace DotNetNuke &#39;*********************************
Ok so you have all seen them: “8 million tools for web development”, “5 gagillion tools that if you