在WebAPI自定义操作过滤器中获取Request.UserHostAddress时,为什么总是获得相同的IP?

Jas*_*son 5 c# action-filter asp.net-web-api

我已经创建了一个Web API自定义操作过滤器来记录传入的调用.我正在尝试获取呼叫者的IP地址以及我发现的所有内容Request.UserHostAddress.问题在于,无论呼叫来自何处,IP都是相同的.

这是我的动作过滤器的代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

var caller = ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.ServerVariables["REMOTE_ADDR"].ToString();
Run Code Online (Sandbox Code Playgroud)

但结果是一样的.有任何想法吗?

Jas*_*son 7

在这里找到答案:HttpContext.Current.Request.UserHostAddress为null.

基本上,我需要理清转发.最终的代码是:

    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);
    }
Run Code Online (Sandbox Code Playgroud)

感谢大家.我会在2天内将它标记为答案.