[英]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...
}
使用C#和ASP.NET
只是一個警告。 IP地址不能用於唯一標識客戶端。 NAT防火牆和企業代理無處不在,並且將許多用戶隱藏在單個IP之后。
嘗試:
Context.Request.UserHostAddress
試試這個:
string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
沒有在webMethod中嘗試過,但我在標准的HttpRequests中使用它
HttpContext實際上在WebService
基類中可用,因此只需使用Context.Request
(或指向當前上下文的HttpContext.Current
)來訪問HttpRequest
提供的成員。
我做了以下功能:
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,如果您有一些代理或自然,您應該研究原始IP是否被移動到http數據包中的其他位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.