相当于用户IP地址的HttpContext

时间:2018-03-28 15:38:04

标签: c# wcf

我正在使用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);
}

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

1 个答案:

答案 0 :(得分:0)

我找到了使用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);