I have application based on this tutorial
Method I use to test connection to server (in client app):
public class PBMBService : IService
{
private void btnPing_Click(object sender, EventArgs e)
{
ServiceClient service = new ServiceClient();
tbInfo.Text = service.Ping().Replace("\n", "\r\n");
service.Close();
}
//other methods
}
Service main function:
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8000/PBMB");
ServiceHost selfHost = new ServiceHost(typeof(PBMBService), baseAddress);
try
{
selfHost.AddServiceEndpoint(
typeof(IService),
new WSHttpBinding(),
"PBMBService");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
selfH开发者_JS百科ost.Open();
Console.WriteLine("Serwis gotowy.");
Console.WriteLine("Naciśnij <ENTER> aby zamknąć serwis.");
Console.WriteLine();
Console.ReadLine();
selfHost.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("Nastąpił wyjątek: {0}", ce.Message);
selfHost.Abort();
}
}
}
Ping() function decaration
[ServiceContract(Namespace = "http://PBMB")]
public interface IService
{
[OperationContract]
string Ping();
}
Ping() function implementation
public class PBMBService : IService
{
SqlConnection sql = new SqlConnection(@"Data Source=.\SqlExpress;Initial Catalog=PBMB;Integrated Security=True");
SqlCommand cmd;
private void Message(string message)
{
Console.WriteLine(DateTime.Now + " -> " + message);
}
public string Ping()
{
Message("Ping()");
return "Metoda Ping() działa.";
}
}
How can I put caller's IP in Message method?
The original blog is available through the Wayback Machine. Note that you'll need to be using WCF 3.5 or later per the author's post.
The code from the article is below;
Service Contract
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace ClientInfoSample
{
[ServiceContract]
public interface IService
{
[OperationContract]
string GetData(string value);
}
}
Implementation with retrieving IP:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Channels;
namespace ClientInfoSample
{
public class MyService : IService
{
public string GetData(string value)
{
OperationContext context = OperationContext.Current;
MessageProperties messageProperties = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
return string.Format("Hello {0}! Your IP address is {1} and your port is {2}", value, endpointProperty.Address, endpointProperty.Port);
}
}
}
Are you looking for something like
HttpContext.Current.Request.UserHostAddress
精彩评论