public
Created

WCF Rest Client/Server

  • Download Gist
ClientProgram.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
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);
}
}
}
}
ServerProgram.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
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();
}
}
}
}
app.config
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
<?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>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.