实现起来很简单,一个Filter就可以搞定!!!

    /// <summary>
/// 监控接口执行时间
/// </summary>
public class TimingActionFilter : ActionFilterAttribute
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
private const string Key = "__action_duration__"; /// <summary>
/// 启用计时器
/// </summary>
/// <param name="actionContext"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
/*
await Trace.WriteAsync("Executing action named {0} for request {1}.",
actionContext.ActionDescriptor.ActionName,actionContext.Request.GetCorrelationId());
*/
if (SkipLogging(actionContext))
{
return base.OnActionExecutingAsync(actionContext, cancellationToken);
}
var stopWatch = new Stopwatch();
actionContext.Request.Properties[Key] = stopWatch;
stopWatch.Start();
return base.OnActionExecutingAsync(actionContext, cancellationToken);
} /// <summary>
/// 记录监控接口执行日志
/// </summary>
/// <param name="actionExecutedContext"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
{
if (!actionExecutedContext.Request.Properties.ContainsKey(Key))
{
return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
}
var stopWatch = actionExecutedContext.Request.Properties[Key] as Stopwatch;
if (stopWatch != null)
{
stopWatch.Stop();
var actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
var controllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
string log = string.Format("[execution controller:{0} - action:{1} take {2} time.]", controllerName, actionName, stopWatch.Elapsed);
#if DEBUG
Debug.Print(log);
#endif
logger.Info(log);
}
return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
} private static bool SkipLogging(HttpActionContext actionContext)
{
return actionContext.ActionDescriptor.GetCustomAttributes<NoLogAttribute>().Any() || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<NoLogAttribute>().Any();
}
} /// <summary>
/// 不记录监控接口执行日志
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true)]
public class NoLogAttribute : Attribute
{ }

WebApiConfig中启用

public static void Register(HttpConfiguration config)
{
//启用监控接口执行时间
//config.Filters.Add(new TimingActionFilter());
//启用全局验证
config.Filters.Add(new ModelValidFilter());
//启用特性路由
config.MapHttpAttributeRoutes(); //默认路由
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}

配置NLog记录响应时间超过1秒的接口服务

  <target name="database" xsi:type="Database" connectionString="Data Source=xxx;Initial Catalog=WebAPI_Log;Persist Security Info=True;User ID=xxx;Password=xxx"  commandText="insert into [WebAPI_Log]([CreateOn],[Origin],[LogLevel], [Message], [Exception],[StackTrace]) values (getdate(), @origin, @logLevel, @message,@exception, @stackTrace);">
<!--日志来源-->
<parameter name="@origin" layout="${callsite}"/>
<!--日志等级-->
<parameter name="@logLevel" layout="${level}"/>
<!--日志消息-->
<parameter name="@message" layout="${message}"/>
<!--异常信息-->
<parameter name="@exception" layout="${exception}" />
<!--堆栈信息-->
<parameter name="@stackTrace" layout="${stacktrace}"/>
</target>

Refer:

http://www.cnblogs.com/shanyou/p/3308058.html

http://stackoverflow.com/questions/14062028/how-to-intercept-all-the-asp-net-webapi-controller-action-methods-calls-with-nin

记录ASP.NET Web API 服务接口响应时间的更多相关文章

  1. 使用HttpClient对ASP.NET Web API服务实现增删改查

    本篇体验使用HttpClient对ASP.NET Web API服务实现增删改查. 创建ASP.NET Web API项目 新建项目,选择"ASP.NET MVC 4 Web应用程序&quo ...

  2. 使用HttpClient消费ASP.NET Web API服务

    本篇体验使用HttpClient消费ASP.NET Web API服务,例子比较简单. 依次点击"文件","新建","项目". 选择&quo ...

  3. ASP.NET Web Api 2 接口API文档美化之Swagger

    使用第三方提供的swgger ui 可有效提高 web api 接口列表的阅读性,并且可以在页面中测试服务接口. 但本人在查阅大量资料并进行编码测试后,发现大部分的swagger实例并不能有效运行.例 ...

  4. ASP.NET Web API编程——接口安全与角色控制

    1 API接口验证与授权 JWT JWT定义,它包含三部分:header,payload,signature:每一部分都是使用Base64编码的JSON字符串.之间以句号分隔.signature是”h ...

  5. asp.net web api 的版本升级到 2.2的记录

    asp.net web api 的版本 升级到 2.2的记录 asp.net web api 2.2相比1.0提升了不少 而且其中最重要的就是有了在线文档的自动字段注释的功能 再也不用写详细的字段说明 ...

  6. ASP.NET Web API——选择Web API还是WCF

    WCF是.NET平台服务开发的一站式框架,那么为什么还要有ASP.NET Web API呢?简单来说,ASP.NET Web API的设计和构建只考虑了一件事情,那就是HTTP,而WCF的设计主要是考 ...

  7. 基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD)

    一些小的C/S项目(winform.WPF等),因需要访问操作数据库,但又不能把DB连接配置在客户端上,原因有很多,可能是DB连接无法直接访问,或客户端不想安装各种DB访问组件,或DB连接不想暴露在客 ...

  8. Web API 2 入门——使用ASP.NET Web API和Angular.js构建单页应用程序(SPA)(谷歌翻译)

    在这篇文章中 概观 演习 概要 由网络营 下载网络营训练包 在传统的Web应用程序中,客户机(浏览器)通过请求页面启动与服务器的通信.然后,服务器处理请求,并将页面的HTML发送给客户端.在与页面的后 ...

  9. 适用于app.config与web.config的ConfigUtil读写工具类 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类) 基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式

    适用于app.config与web.config的ConfigUtil读写工具类   之前文章:<两种读写配置文件的方案(app.config与web.config通用)>,现在重新整理一 ...

随机推荐

  1. linux C学习笔记02--共享内存(进程同步)

    system V下3中进程同步:共享内存(shared memory),信号量(semaphore)和消息队列(message queue) 调试了下午,终于调通啦! 运行./c.out 输出共享内存 ...

  2. smarty模板的安装配置

    第一步:下载Smarty模版源码包了    百度一下“Smarty下载”,下载最新版本的Smarty模版第二部:解压缩,将下载好的Smarty包解压缩    右键->解压到当前文件夹...你懂的 ...

  3. 读取jar包资源(转)

    可能有不少初学者会有这样的困惑:在你的代码里调用了一些资源文件,如图片,音乐等,在调试环境或单独运行的时候可以正常显示或播放,而一旦打包到jar文件中,这些东东就再也出不来了,除非把这个jar放到原来 ...

  4. git init 和 git init --bare 的区别

    http://blog.csdn.net/ljchlx/article/details/21805231 概念  裸仓储 :不可以在上面做git操作    the operation must be ...

  5. 循序渐进Python3(三) -- 0 -- 初识函数

    函数 如果我们要计算一个圆的面积,就需要知道它的半径,然后根据公式S=3.14*r*r算出它的面积,如果我们要算100个圆的面积,则每次我们都需要写公式去计算,是不是很麻烦,但是有了函数的话,我们就不 ...

  6. vnc

    Xvnc, Xvnc-core, vncagent, vncinitconfig, vnclicense, vnclicensehelper, vnclicensewiz, vncpasswd, vn ...

  7. C++(MFC)中WebBrowser去除3D边框的方法(实现IDocHostUIHandler接口)控制 WebBrowser 控件的外观和行为

    在 CSDN 上经常看到以下两个问题:1.在 MFC 应用程序中,如果创建了一个 WebBrowser 控件(包括 CHtmlView 在内),如何可以把该控件的三维边框禁止掉?2.在 MFC 应用程 ...

  8. 何修改WAMP中mysql默认空密码--转

    何修改WAMP中mysql默认空密码  http://www.cnblogs.com/hooray/archive/2011/07/23/2114792.html WAMP安装好后,mysql密码是为 ...

  9. POJ2762 UV

    题意:n个山洞,对于每两个山洞s,e,都满足s可以到达e或者e可以到达s,则输出Yes,否则输出No. ---------------------------------------- 第一个缩点的题 ...

  10. json传值以及ajax接收

    一开始进入公司,做起项目来比较不知所措,现在一个月过去了,越来越得心应手,下面是json向前端传值以及前端ajax接收,给自己记下也分享给大家. 这是两个类型不同的json与ajax的数据交互(集合. ...