Why do I always get the same IP when getting Request.UserHostAddress in WebAPI custom action filter?
action-filter, asp.net-web-api, c#
Solution
Found the answer here: HttpContext.Current.Request.UserHostAddress is null.
Basically, I needed to sort out the forwarding. The final code is:
public override void OnActionExecuting(HttpActionContext actionContext)
{
var name = actionContext.ActionDescriptor.ActionName;
// Get the sender address
var myRequest = ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request;
var ip = myRequest.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ip))
{
string[] ipRange = ip.Split(',');
int le = ipRange.Length - 1;
string trueIP = ipRange[le];
}
else
{
ip = myRequest.ServerVariables["REMOTE_ADDR"];
}
// Log the call
SystemBL.InsertSiteLog("WebAPI:" + name, "From:" + ip);
}
Thanks everyone. I'll mark it as the answer in 2 days when it lets me.
Problem
I've created a Web API custom action filter to log incoming calls. I'm trying to get the caller's IP address and everything I've found says to use `Request.UserHostAddress`. The problem is that no matter where the call is coming from, the IP is the same. Here's the code for my action filter: ``` public class LogActionFilter : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { var name = actionContext.ActionDescriptor.ActionName; // Get the sender address var caller = ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.UserHostAddress; // Log the call SystemBL.InsertSiteLog("WebAPI:" + name, "From:" + caller); } } ``` I've also tried with: ``` var caller = ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.ServerVariables["REMOTE_ADDR"].ToString(); ``` but the result was the same. Any ideas?