简体   繁体   中英

Client IP address in UserNamePasswordValidator

I have a WCF REST rest service, that is hosted by a Windows Service. It uses custom UserNamePasswordValidator authentication.

I'd like to get client ip address when authenticating:

ublic static string GetClientIPAddress()
    {
        try
        {
            var context = OperationContext.Current;
            var prop = context.IncomingMessageProperties;
            var endpoint = prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
            return endpoint.Address;
        }
        catch (System.Exception exc)
        {
            Debug.Assert(false,exc.Message);
            return string.Empty;
        }
    }

But it throws an exception, because context is null in that case. How can I solve this? Note, the mostly suggested asp.net compatibility mode is not an option, my service is hosted by a WIndows Service, NOT by IIS.

Thanks!

Heey try that solution that should work .

private string GetClientIp(HttpRequestMessage request)
{
    if (request.Properties.ContainsKey("MS_HttpContext"))
    {
        return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
    }
    else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
    {
        RemoteEndpointMessageProperty prop;
        prop = (RemoteEndpointMessageProperty)this.Request.Properties[RemoteEndpointMessageProperty.Name];
        return prop.Address;
    }
    else
    {
        return null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM