Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I always get the same IP when getting Request.UserHostAddress in WebAPI custom action filter?

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?

like image 286
Jason Avatar asked Apr 01 '14 20:04

Jason


People also ask

How do I use action filter in Web API?

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.

What are the Web API filters?

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.


1 Answers

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.

like image 148
Jason Avatar answered Oct 02 '22 22:10

Jason