在Web服务中获取客户端IP

时间:2014-12-03 14:34:58

标签: c# web-services

我在控制台应用程序中有简单的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?

2 个答案:

答案 0 :(得分:0)

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

试试这个

MessageProperties props = OperationContext.Current.IncomingMessageProperties;

RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)props[RemoteEndpointMessageProperty.Name];

string addr = prop.Address;
int iPort   = prop.Port;

答案 1 :(得分:0)

您的方法适用于网络托管版本, 自我托管尝试

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

请参阅here了解文档