ActionFilterAttribute 全局记录API日志

1、API项目下创建MonitorApiAttribute

public class MonitorApiAttribute : ActionFilterAttribute
{
private static readonly string key = "enterTime"; public override void OnActionExecuted(HttpActionExecutedContext filterContext)
{
try
{
object beginTime = null;
if (filterContext.Request.Properties.TryGetValue(key, out beginTime))
{
var user = HttpContext.Current.User as UserInfo;//登录时储存的User
var indentify = user != null ? user.Id.ToString() : null; MonitorApiHelper.Monitor(beginTime, filterContext.Request, filterContext.Response, indentify);
}
}
catch (Exception)
{
} base.OnActionExecuted(filterContext);
} public override void OnActionExecuting(HttpActionContext actionContext)
{
actionContext.Request.Properties[key] = DateTime.Now.ToBinary(); base.OnActionExecuting(actionContext);
}
}

2、Common项目下创建MonitorApiHelper帮助类

public class MonitorApiHelper
{ public static async void Monitor(object beginTime, HttpRequestMessage httpRequestMessage, HttpResponseMessage httpResponseMessage, string indentify = "", string moduleId = "")
{
DateTime time = DateTime.FromBinary(Convert.ToInt64(beginTime));
var responseTime = Convert.ToInt32((DateTime.Now - time).TotalMilliseconds); var appId = "myapp";
var clientType = 0;
var responseStatus = 0; var request = HttpContext.Current.Request;
var browerVersion = request.UserAgent;
var clientIP = request.UserHostAddress;
var serviceName = request.Url.AbsoluteUri;
var requestType = MethodConver(request.HttpMethod); var inputParams = ReadStream(await httpRequestMessage.Content.ReadAsStreamAsync());
var outputParams = ReadStream(await httpResponseMessage.Content.ReadAsStreamAsync()); //在这里使用以上变量记录日志操作
} private static int MethodConver(string method)
{
switch (method.ToUpper())
{
case "GET":
return 0;
case "POST":
return 1;
case "PUT":
return 2;
case "DELETE":
return 3;
default:
break;
}
return 0;
} public static string ReadStream(Stream stream)
{
var content = string.Empty;
if (stream != null)
{
stream.Seek(0, SeekOrigin.Begin);
int len = (int)stream.Length;
byte[] inputByts = new byte[len];
stream.Read(inputByts, 0, len);
stream.Position = 0;
content = Encoding.UTF8.GetString(inputByts);
} return content;
}
}

3、WebApiConfig下增加代码  config.Filters.Add(new MonitorApiAttribute());

  public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services // Web API routes
config.MapHttpAttributeRoutes(); config.Filters.Add(new MonitorApiAttribute()); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
上一篇:sqlserver2008安装教程


下一篇:yii2框架-yii2局部关闭(开启)csrf的验证