C# 如何接通来电者';WebMethod中的IP地址?
如何在WebMethod中获取调用方的IP地址C# 如何接通来电者';WebMethod中的IP地址?,c#,asp.net,web-services,C#,Asp.net,Web Services,如何在WebMethod中获取调用方的IP地址 [WebMethod] public void Foo() { // HttpRequest... ? - Not giving me any options through intellisense... } 使用C#和ASP.NET是您想要的。HttpContext实际上在WebService基类中可用,所以只需使用Context.Request(或HttpContext.Current,它也指向当前上下文)要访问由HttpReque
[WebMethod]
public void Foo()
{
// HttpRequest... ? - Not giving me any options through intellisense...
}
使用C#和ASP.NET是您想要的。HttpContext实际上在
WebService
基类中可用,所以只需使用Context.Request
(或HttpContext.Current
,它也指向当前上下文)要访问由HttpRequest提供的成员,请尝试以下操作:
string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
还没有在webMethod中尝试过,但我在标准的HttpRequests中使用了它
Context.Request.UserHostAddress
只是提醒一下。IP地址不能用于唯一标识客户端。NAT防火墙和公司代理无处不在,将许多用户隐藏在一个IP后面。我实现了以下功能:
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";
}
}
这只适用于Intranet,如果您有代理或natting,您应该研究原始IP是否在http数据包中移动到其他位置。如果您获得System.InvalidOperationException“HttpContext不可用。此类只能在ASP.NET请求的上下文中使用。”如果不向web.config添加某些内容,则上下文中的HttpContext将不可用。另外,所有HTTP头都可以很容易地被欺骗。将有效数据放入其中的代码可以用于将无效数据放入其中。