2012-07-06 88 views
-1

我正在嘗試在我的Web服務中創建一個方法,該方法將記錄服務中每個方法的每個請求的IP地址。我試圖使用HttpContext,但無論我做什麼,都會返回一個空引用異常。我希望能夠從請求中獲取IP並將其記錄到SQL數據庫中。以下是我試圖記錄的一種方法的示例。WCF Web服務IP記錄

public GetPL GPL(string code) 
    { 
     var db = new TDCDataContext(); 

     var pq = db.PROC_SELECT_GPL(code).ToList(); 

     //a bunch of nonsense 

     //logging 
     var ip = HttpContext.Current.Request.UserHostAddress; 
     var method = GetMethod(); 
     db.PROC_INSERT_Log(ip, code, method, true, null, null); 

     return stuff; 
    } 

我是否在錯誤的方向?

+0

可能重複看到:http://stackoverflow.com/questions/93162/obtaining-client-ip-address-in-wcf-3-0 – 2012-07-06 15:33:13

+0

取決於你用什麼協議,您的WCF服務將只能訪問HttpContext,如果a)您正在託管RESTFUL服務,b)您是ASP.NET兼容的,以及c)您的請求通過GET或POST發送。正常的WCF調用不會使用HttpContext – 2012-07-06 18:43:25

回答

1
   try 
       { 
        var context = OperationContext.Current; 
        if (context != null) 
        { 
         var prop = context.IncomingMessageProperties; 

         if (prop != null && 
          !string.IsNullOrEmpty(RemoteEndpointMessageProperty.Name) && 
          prop.ContainsKey(RemoteEndpointMessageProperty.Name)) 
         { 
          endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; 
         } 
        }      
       } 
       catch (Exception e) 
       { 
        //log 
       } 

//endpoint.Address - ip address