C# 如何在 WebMethod 中获取调用者的 IP 地址?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/130328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 14:54:05  来源:igfitidea点击:

How do I get the caller's IP address in a WebMethod?

提问by Guy

How do I get the caller's IP address in a WebMethod?

如何在 WebMethod 中获取调用者的 IP 地址?

[WebMethod]
public void Foo()
{
    // HttpRequest... ? - Not giving me any options through intellisense...
}

using C# and ASP.NET

使用 C# 和 ASP.NET

采纳答案by Darren Kopp

回答by Troels Thomsen

The HttpContext is actually available inside the WebServicebase class, so just use Context.Request(or HttpContext.Currentwhich also points to the current context) to get access to the members provided by the HttpRequest.

HttpContext 实际上在WebService基类内部可用,因此只需使用Context.Request(或HttpContext.Current它也指向当前上下文)来访问HttpRequest.

回答by Aaron Powell

Try this:

尝试这个:

string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

Haven't tried it in a webMethod, but I use it in standard HttpRequests

没有在 webMethod 中尝试过,但我在标准 HttpRequests 中使用它

回答by Kev

Try:

尝试:

Context.Request.UserHostAddress

回答by davenpcj

Just a caution. IP addresses can't be used to uniquely identify clients. NAT Firewalls and corporate proxies are everywhere, and hide many users behind a single IP.

只是一个警告。IP 地址不能用于唯一标识客户端。NAT 防火墙和公司代理无处不在,将许多用户隐藏在一个 IP 后面。

回答by depoip

I made the following function:

我做了以下功能:

static public string sGetIP()
{
    try
    {
        string functionReturnValue = null;

        String oRequestHttp =
            WebOperationContext.Current.IncomingRequest.Headers["User-Host-Address"];
        if (string.IsNullOrEmpty(oRequestHttp))
        {
            OperationContext context = OperationContext.Current;
            MessageProperties prop = context.IncomingMessageProperties;
            RemoteEndpointMessageProperty endpoint =
                prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
            oRequestHttp = endpoint.Address;
        }
        return functionReturnValue;
    }
    catch (Exception ex)
        {
            return "unknown IP";
        }
}

This work only in Intranet, if you have some Proxy or natting you should study if the original IP is moved somewhere else in the http packet.

这仅在 Intranet 中工作,如果您有一些 Proxy 或 natting,您应该研究原始 IP 是否移动到 http 数据包中的其他位置。