【问题标题】:Equivalent to HttpContext for user IP address [duplicate]等效于用户 IP 地址的 HttpContext [重复]
【发布时间】:2018-03-28 15:38:03
【问题描述】:

我在做 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 地址?

【问题讨论】:

  • 我同意 - 重复问题的答案取决于版本。

标签: c# wcf


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-07-21
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 2020-04-10
    • 2014-01-25
    • 2012-07-18
    • 2013-03-19
    • 2012-12-05
    相关资源
    最近更新 更多