代码之家  ›  专栏  ›  技术社区  ›  A.Pissicat

相当于用户IP地址的HttpContext[重复]

  •  0
  • A.Pissicat  · 技术社区  · 7 年前

    我正在研究C#WCF,我必须修改一段代码。

    基本代码包含:

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        string ipAddress = HttpContext.Current.Request.UserHostAddress;
        WinEventLog.logInfo("Connection from : " + ipAddress);
        bool test = IsIpAddressAllowed(ipAddress.Trim());
        [..]
    }
    
    private bool IsIpAddressAllowed(string IpAddress)
    {
        [..]
    }
    

    但在WCF中,我无法获得 HttpContext.Current.Request.UserHostAddress

    我的WCF代码是:

    [ServiceContract]
    [RequiredParametersBehavior]
    public interface IMyService
    {
        [OperationContract]
        String Request(String environment, String request);
    }
    

    如何在函数中获取用户IP地址 Request ?

    1 回复  |  直到 7 年前
        1
  •  0
  •   A.Pissicat    6 年前

    我找到了一个解决方案 OperationContext

    我的方法是:

    private bool IsIpAddressAllowed(string IpAddress)
    {
        MessageProperties prop = context.IncomingMessageProperties;
        RemoteEndpointMessageProperty endpoint =
            prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
    
        String ipAddress = endpoint.Address; // Here I get the IP
    
        WinEventLog.EventLog.logInfo(null, "Connection from : " + ipAddress);
    
        return MyTestOnIP(ipAddress);
    }
    

    这样称呼:

    bool isOK = IsIpAddressAllowed(System.ServiceModel.OperationContext.Current);