I have simple web service in console application:
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();
}
}
Service interface and class:
[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;
}
}
Trying to get clients IP in line:
String IP = HttpContext.Current.Request.UserHostAddress;
But Current
is NULL
and I have exception. How to get client IP in my project case?