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?
Action filters contain logic that is executed before and after a controller action executes. You can use an action filter, for instance, to modify the view data that a controller action returns. Result filters contain logic that is executed before and after a view result is executed.
Web API includes filters to add extra logic before or after action method executes. Filters can be used to provide cross-cutting features such as logging, exception handling, performance measurement, authentication and authorization.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With