Posterous theme by Cory Watilo

Self hosting WCF 4 REST stories

I've figured out how to create a ServiceHost that will do REST work with GET/POST/PUT and I assume DELETE as well.  Just haven't tried that.

Using the WebServiceHost alone will create 405 errors for POST and PUT.  Do that, there is the aptly named "enableWebScript" endpoint behavior to use in the config file.  But I abhor WCF xml configuration so doing it through code looks like this:

 

WebServiceHost host = new WebServiceHost(typeof(Clazz), new Uri("http://localhost:5150/"));
if (!host.Description.Behaviors.OfType<ServiceDebugBehavior>().Any())
{
        host.Description.Behaviors.Add(new ServiceDebugBehavior()
        {
                IncludeExceptionDetailInFaults = true
        });
}
if (!host.Description.Behaviors.OfType<ServiceMetadataBehavior>().Any())
{
        host.Description.Behaviors.Add(new ServiceMetadataBehavior()
        {
                HttpGetEnabled = true
        });
}
host.Description.Endpoints.ForEach(e => e.Behaviors.Add(new WebScriptEnablingBehavior()
        {
                FaultExceptionEnabled = true,
                DefaultOutgoingRequestFormat = WebMessageFormat.Json,
                DefaultOutgoingResponseFormat = WebMessageFormat.Json,
        }));
host.Open();

I wanted to be Json by default too.

Also, you can use the same base URI (i.e. localhost) and just append a path name to the webhost to use multiple contracts with the same domain.  So you have a class named Clazz1 with a WebGet method for "/stuff/" and open the host with the base URI "http://localhost/Clazz1" then it's available for the complete URI being "http://localhost/Clazz1/stuff/"  Then you can open a second host for Clazz2 on "http://localhost/Clazz2" and address it's methods there.

Hopefully, all of this figuring it isn't needed when the WCF HTTP future project is more mature.