-1

我正在尝试在我的 Web 服务中创建一个方法,该方法将记录服务中每个方法的每个请求的 IP。我尝试使用 HttpContext,但无论我做什么,它都会返回一个空引用异常。我希望能够从请求中获取 IP 并将其记录到 SQL 数据库中。这是我尝试记录的一种方法的示例。

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;
    }

我是不是走错了方向?

4

1 回答 1

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

于 2012-07-06T15:29:39.263 回答