Skip to content

Instantly share code, notes, and snippets.

@scottmcarthur
Created March 7, 2014 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottmcarthur/9408411 to your computer and use it in GitHub Desktop.
Save scottmcarthur/9408411 to your computer and use it in GitHub Desktop.
Example of Custom Serialization in ServiceStack v4.
using System;
using ServiceStack;
using ServiceStack.Web;
namespace CustomSerializerTest
{
class MainClass
{
public static void Main()
{
var appHost = new AppHost(500);
appHost.Init();
appHost.Start("http://*:9000/");
Console.ReadKey();
}
}
public class AppHost : AppHostHttpListenerPoolBase
{
public AppHost(int poolSize) : base("Test Service", poolSize, typeof(TestService).Assembly)
{
}
public override void Configure(Funq.Container container)
{
SetConfig(new HostConfig {
DebugMode = true,
//DefaultContentType = "application/xml"
});
StreamSerializerDelegate serialize = (request, response, stream) => {
// Dummy custom serialization method, nothing fancy
// Replace with call to your serializer
var o = response as IMyCustomResponse;
if(o == null) throw new Exception("Not the expected type");
stream.Write(string.Format("<CustomMessage Test=\"{0}\">{1}</CustomMessage>", DateTime.Now.Ticks, o.Message));
};
StreamDeserializerDelegate deserialize = (type, fromStream) => { throw new NotImplementedException(); };
ContentTypes.Register("application/xml", serialize, deserialize);
}
}
[FallbackRoute("/{Path*}")]
public class RootRequest : IReturn<TestResponse>
{
public string Path { get; set; }
}
[Route("/Test", "GET")]
public class TestRequest : IReturn<TestResponse>
{
}
public interface IMyCustomResponse
{
string Message { get; set; }
}
public class TestResponse : IMyCustomResponse
{
public string Message { get; set; }
}
public class TestService : Service
{
[AddHeader(ContentType = "application/xml")]
public TestResponse Get(RootRequest request)
{
return new TestResponse { Message = "Hello from root" };
}
[AddHeader(ContentType = "application/xml")]
public TestResponse Get(TestRequest request)
{
return new TestResponse { Message = "Hello from test" };
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment