Skip to content

Instantly share code, notes, and snippets.

@kalebpederson
Created August 18, 2012 00:42
Show Gist options
  • Save kalebpederson/3383673 to your computer and use it in GitHub Desktop.
Save kalebpederson/3383673 to your computer and use it in GitHub Desktop.
WCF Rest Client/Server
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="ServiceConsole.Service" behaviorConfiguration="SampleService.ServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/SampleService.Service/"/>
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint
address="http://localhost:8000/SampleService.Service/"
binding="webHttpBinding"
behaviorConfiguration="xmlorjsonBehavior"
contract="ServiceConsole.IService">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="xmlorjsonBehavior">
<webHttp automaticFormatSelectionEnabled="true" defaultBodyStyle="Bare" />
<!-- json or xml-->
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="SampleService.ServiceBehavior">
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="True"/>
<!-- To receive exception details in faults for debugging purposes,
set the value below to true. Set to false before deployment
to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
namespace WcfRestClient
{
[DataContract(Namespace="")]
public class Data
{
[DataMember]
public string Message { get; set; }
}
[DataContract(Namespace = "")]
public class ErrorDetails
{
[DataMember] public string ErrorMessage { get; set; }
}
[ServiceContract(Namespace="")]
public interface IClient
{
[OperationContract]
[WebInvoke(
UriTemplate="/response",
Method="GET",
// XML - serialization error occurs for status code OK
// XML - unexpected error (communication exception) for status code Conflict
// JSON - response object is returned blank for status code OK
// JSON - unexpected error (communication exception) for status code Conflict
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
[FaultContract(typeof(ErrorDetails), Namespace="")]
Data GetResponse();
}
public class Client : ClientBase<IClient>, IClient
{
public Client(Binding binding, EndpointAddress endpoint) : base( binding, endpoint) { }
public Data GetResponse()
{
return this.Channel.GetResponse();
}
}
public class Program
{
public static void Main(string[] args)
{
try
{
GetErrorResponse();
}
catch (Exception ex)
{
Console.Error.WriteLine("Error: " + ex.Message);
}
Console.WriteLine("Press a key to exit...");
Console.ReadLine();
}
private static void GetErrorResponse()
{
var factory = new ChannelFactory<IClient>(
new WebHttpBinding(),
"http://localhost:8000/SampleService.Service");
var behavior = new WebHttpBehavior();
behavior.AutomaticFormatSelectionEnabled = true;
behavior.DefaultBodyStyle = WebMessageBodyStyle.Bare;
factory.Endpoint.Behaviors.Add(behavior);
var client = factory.CreateChannel();
try
{
Console.WriteLine("Requesting response");
Console.WriteLine("Response: " + client.GetResponse().Message);
Console.WriteLine("Request complete");
}
catch (WebFaultException<ErrorDetails> ex)
{
Console.WriteLine("WebFaultException<ErrorDetails>: " + ex.Detail.ErrorMessage + ", " + ex.Reason);
}
catch (FaultException<ErrorDetails> ex)
{
Console.WriteLine("FaultException<ErrorDetails>: " + ex.Detail.ErrorMessage + ", " + ex.Reason);
}
catch (FaultException ex)
{
Console.WriteLine("FaultException: " + ex.Message + ", " + ex.Reason);
}
catch (CommunicationException ex)
{
Console.WriteLine("CommunicationException: " + ex.Message + ", " + ex.Data + ", " + ex.GetType().FullName);
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message + ", " + ex.Data);
}
}
}
}
using System;
using System.Net;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace ServiceConsole
{
[DataContract(Namespace="")]
public class Data
{
[DataMember]
public string Message { get; set; }
}
[ServiceContract(Namespace = "")]
public interface IService
{
[OperationContract]
[WebGet(UriTemplate = "/response")]
[FaultContract(typeof(ErrorDetails))]
Data GetResponse();
}
[DataContract(Namespace="")]
public class ErrorDetails
{
[DataMember] public string ErrorMessage { get; set; }
}
public class Service : IService
{
public Data GetResponse()
{
throw new WebFaultException<ErrorDetails>(
new ErrorDetails {ErrorMessage = "Server Config Value not set"},
HttpStatusCode.OK
);
}
}
class Program
{
static void Main(string[] args)
{
WebServiceHost host = new WebServiceHost(typeof(Service));
try
{
// request from: http://localhost:8000/SampleService.Service/response
host.Open();
Console.WriteLine("Press <ENTER> to terminate");
Console.ReadLine();
host.Close();
}
catch (CommunicationException cex)
{
Console.WriteLine("An exception occurred: {0}", cex.Message);
host.Abort();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment