Created
March 7, 2014 09:30
-
-
Save scottmcarthur/9408411 to your computer and use it in GitHub Desktop.
Example of Custom Serialization in ServiceStack v4.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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