namespace Pelebyte.ServiceModel.Generic
{
using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
[ServiceContract]
[ServiceBehavior(
InstanceContextMode = InstanceContextMode.Single,
AddressFilterMode = AddressFilterMode.Any)]
public class GenericService
{
///
/// Starts up a generic HTTP service.
///
///
/// Arguments to the event.
///
public static void Main(string[] args)
{
Uri uri = new Uri("http://localhost:9000/");
var serviceImpl = new GenericService();
using (var host = new ServiceHost(serviceImpl))
{
// this gives you a minimal, but workable formatting that handles .NET
// serializable types well, but you don't have complete control over
// what gets sent out
var net35Binding = new CustomBinding(
new TextMessageEncodingBindingElement {MessageVersion = MessageVersion.None},
new HttpTransportBindingElement());
// this gives you complete control over the stream
var net40Binding = new CustomBinding(
new ByteStreamMessageEncodingBindingElement(),
new HttpTransportBindingElement());
var binding = net40Binding; // either net35binding or net40binding
host.AddServiceEndpoint(typeof(GenericService), binding, uri);
// begin listening for connections
host.Open();
// display a little message and wait for the user to kill the console app
Console.WriteLine("Listening on URI: {0}", uri);
Console.WriteLine("Press ENTER to shutdown the service.");
Console.ReadLine();
}
}
[OperationContract(Action = "*", ReplyAction = "*")]
public Message Process(Message message)
{
// this is the incoming URI; we're not doing anything with it
// here, but you will
var uri = message.Headers.To;
// build a stream of bytes that represents the text
// "Test" in UTF-8
var bytes = Encoding.UTF8.GetBytes("Test");
var memStream = new MemoryStream(bytes);
// create and return the response message
return Message.CreateMessage(MessageVersion.None, "OK", new BodyStreamProviderWriter(memStream));
}
}
}