在 Web 服务中获取客户端 IP

本文关键字:客户端 IP 获取 Web 服务 | 更新日期: 2023-09-27 18:33:07

>我在控制台应用程序中有简单的Web服务:

static void Main(string[] args)
        {
            WSHttpBinding binding = new WSHttpBinding();
            binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            binding.Security.Mode = SecurityMode.None;
            Uri baseAddress = new Uri("http://localhost:8001/LogService");
            using (ServiceHost serviceHost =
                new ServiceHost(typeof(MyLogService), baseAddress))
            {
                // Check to see if it already has a ServiceMetadataBehavior
                ServiceMetadataBehavior smb =
                    serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
                if (smb == null)
                    smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy12;
                serviceHost.Description.Behaviors.Add(smb);
                // Add MEX endpoint
                serviceHost.AddServiceEndpoint(
                    ServiceMetadataBehavior.MexContractName,
                    MetadataExchangeBindings.CreateMexHttpBinding(),
                    "mex"
                    );
                serviceHost.AddServiceEndpoint(typeof(ILogService), binding, baseAddress);

                serviceHost.Open();
                Console.WriteLine("The service is running. Press any key to stop.");
                Console.ReadKey();
            }

        }

服务接口和类:

 [ServiceContract]
    interface ILogService
    {
        [OperationContract]
        int LogIt(ref int id, string data, ref LogLevel level);
    }
    class MyLogService : ILogService
    {
        DBLogger dbl = new DBLogger();
        public int LogIt(ref int id, string data, ref LogLevel level)
        {
            try
            {
                String IP = HttpContext.Current.Request.UserHostAddress;
                Console.WriteLine("conneted from host " + IP);
            }
            catch (Exception d)
            {
                Console.WriteLine(d.Message);
            }

            return 0;
        }
    }

尝试让客户端 IP 符合:

String IP = HttpContext.Current.Request.UserHostAddress;

CurrentNULL,我有例外。 如何在我的项目案例中获取客户端 IP?

在 Web 服务中获取客户端 IP

不能使用 HttpContext,因为您没有在 ASP.NET 模式下运行服务。

试试这个

MessageProperties props = OperationContext.Current.IncomingMessageProperties;
RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)props[RemoteEndpointMessageProperty.Name];
string addr = prop.Address;
int iPort   = prop.Port;

您的方法是针对网络托管版本,对于自托管尝试

object property;
Request.Properties.TryGetValue(typeof(RemoteEndpointMessageProperty).FullName, out property);
RemoteEndpointMessageProperty remoteProperty = property as RemoteEndpointMessageProperty;

有关文档,请参阅此处