繁体   English   中英

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

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

我已经创建了一个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);
    }
}

我也尝试过:

var caller = ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.ServerVariables["REMOTE_ADDR"].ToString();

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

在这里找到答案: 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);
    }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM