2008-09-24 81 views

回答

81
+3

如果得到System.InvalidOperationException「HttpContext不可用,該類只能用於ASP.NET請求的上下文中。」 \t Context中的HttpContext不會在沒有向web.config添加任何內容的情況下可用。 Menace 2013-11-13 16:17:07

2

的HttpContext是WebService基類中實際可用的,所以只需使用Context.Request(或HttpContext.Current這也指出了當前上下文),以獲得訪問由HttpRequest提供的成員。

4

試試這個:

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

還沒有一個WebMethod試了一下,我卻用它在標準HTTPRequests的

6

嘗試:

Context.Request.UserHostAddress 
8

只是一個警告。 IP地址不能用於唯一標識客戶端。 NAT防火牆和企業代理無處不在,並將許多用戶隱藏在單一IP之後。

+0

再加上所有的HTTP頭文件都很容易被欺騙。將有效數據放入其中的相同代碼可用於將無效數據放入其中。 – JessieArr 2017-01-31 22:30:25

0

我做了以下功能:

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數據包你應該學習。