2012-07-06 168 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