73 lines
3.2 KiB
C#
73 lines
3.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net.Http;
|
|
using System.ServiceModel.Channels;
|
|
using System.Threading;
|
|
using System.Web;
|
|
using System.Web.Http.Filters;
|
|
|
|
namespace Weee.Filter
|
|
{
|
|
public class ApiLogAttribute : ActionFilterAttribute, IActionFilter
|
|
{
|
|
private string _ActionDisplayName;
|
|
private string _ModuleDisplayName;
|
|
public ApiLogAttribute(string ActionDisplayName = null, string ModuleDisplayName = null)
|
|
{
|
|
_ActionDisplayName = ActionDisplayName;
|
|
_ModuleDisplayName = ModuleDisplayName;
|
|
}
|
|
|
|
public override System.Threading.Tasks.Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
|
|
{
|
|
var username = actionExecutedContext.ActionContext.ControllerContext.RequestContext.Principal == null ? "" : actionExecutedContext.ActionContext.ControllerContext.RequestContext.Principal.Identity.Name;
|
|
String message =
|
|
String.Format(
|
|
"Method=[{0}] ,User=[{1}], Action=[{2}], Controller=[{3}], IPAddress=[{4}]" +
|
|
"TimeStamp=[{5}]",
|
|
"OnActionExecuted",
|
|
username,
|
|
_ActionDisplayName??actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
|
|
_ModuleDisplayName??actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName,
|
|
GetClientIp(actionExecutedContext.Request),
|
|
DateTime.Now);
|
|
|
|
System.Diagnostics.Debug.WriteLine(message);
|
|
var db = actionExecutedContext.ActionContext.Request.GetDependencyScope().GetService(typeof(Weee.DAL.WeeeDataContext)) as Weee.DAL.WeeeDataContext;
|
|
var log = new Weee.Models.ActionLog()
|
|
{
|
|
Name = username,
|
|
Action = _ActionDisplayName??actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
|
|
Controller = _ModuleDisplayName??actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName,
|
|
IP = GetClientIp(actionExecutedContext.Request),
|
|
ActionTime = DateTime.Now,
|
|
ExecuteResult = actionExecutedContext.Exception == null ? "success" : "exception: " + actionExecutedContext.Exception.Message
|
|
};
|
|
db.ActionLogs.Add(log);
|
|
db.SaveChanges();
|
|
|
|
|
|
return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
|
|
}
|
|
|
|
private string GetClientIp(HttpRequestMessage request)
|
|
{
|
|
if (request.Properties.ContainsKey("MS_HttpContext"))
|
|
{
|
|
return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
|
|
}
|
|
else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
|
|
{
|
|
RemoteEndpointMessageProperty prop;
|
|
prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
|
|
return prop.Address;
|
|
}
|
|
else
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
}
|
|
|
|
} |