Пробуйте использовать код ниже.
UPDATE: Для asp.net Web API, пожалуйста, попробуйте это
public class AuditAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var context = actionContext.RequestContext;
var user = context.Principal.Identity.IsAuthenticated ? context.Principal.Identity.Name : string.Empty;
var ip = GetClientIpAddress(actionContext.Request);
var action = actionContext.ActionDescriptor.ActionName;
var controller = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
base.OnActionExecuting(actionContext);
}
private string GetClientIpAddress(HttpRequestMessage request)
{
if (request.Properties.ContainsKey("MS_HttpContext"))
{
return IPAddress.Parse(((HttpContextBase)request.Properties["MS_HttpContext"]).Request.UserHostAddress).ToString();
}
if (request.Properties.ContainsKey("MS_OwinContext"))
{
return IPAddress.Parse(((OwinContext)request.Properties["MS_OwinContext"]).Request.RemoteIpAddress).ToString();
}
return String.Empty;
}
}
И для asp.net MVC, вы можете попробовать это
public class AuditAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// get user name + ip address + controlleraction
var controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
var action = filterContext.ActionDescriptor.ActionName;
var ip = filterContext.HttpContext.Request.UserHostAddress;
var dateTime = filterContext.HttpContext.Timestamp;
var user = GetUserName(filterContext.HttpContext);
}
private string GetUserName(HttpContext httpContext)
{
var userName = string.Empty;
var context = httpContext.Current;
if (context != null && context.User != null && context.User.Identity.IsAuthenticated)
{
userName = context.User.Identity.Name;
}
else
{
var threadPincipal = Thread.CurrentPrincipal;
if (threadPincipal != null && threadPincipal.Identity.IsAuthenticated)
{
userName = threadPincipal.Identity.Name;
}
}
return userName;
}
}
Update 2: ВОССТАНОВЛЕНИЕ IP-адрес клиента всегда является сложным делом, потому что есть много факторов, которые необходимо учитывать. Как клиенты обращаются к приложению? Они идут через прокси-сервер? IP-адреса могут быть подделаны, поэтому нет надежного способа на 100%. Глядя на Http Headers, вы получите некоторый уровень успеха как в веб-api, так и в mvc. Но вы всегда должны учитывать тот факт, что будут случаи, когда клиентский IP недействителен.
How can I get the client's IP address in ASP.NET MVC?
Является ли проект WebAPI или MVC? – Aamir