5

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?

Liam
  • 27,717
  • 28
  • 128
  • 190
Jason
  • 2,455
  • 4
  • 37
  • 48

1 Answers1

7

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.

Community
  • 1
  • 1
Jason
  • 2,455
  • 4
  • 37
  • 48
  • Is it better to use the HttpActionContext parameter like here and receiving the IP or the better solution is to use static method which uses HttpContext like here: [link](https://stackoverflow.com/questions/1907195/how-to-get-ip-address) I'm not sure what approach shall I chose. – krypru Jan 14 '16 at 10:12
  • 1
    It's been a while since I did this but I think it depends on where you're using it. In my case I was doing it in a filter attribute which doesn't have access to the current context from HttpContext. If you are doing it in a regular MVC action then I would say use the HttpContext as it seems a bit cleaner. Just don't forget to do the address parsing and use the last ip in the list. – Jason Jan 14 '16 at 15:14
  • 1
    You have a bug there, trueIp-variable is never used. Maybe you wanted to assign it to the ip-variable? – Esko Jun 23 '20 at 10:27