When you create a WCF REST Service, the caller of the service wants you to return specific HTTP Status Codes for specific situations such as where there is no data to return in a search query he want to return HTTP 204 No Content. In this article we will show you how to create a WCF REST Service and how to return some common HTTP Status Codes from your service.
Create a WCF REST Service
Add & configure CustomerInfo Data Contract
using System.Runtime.Serialization;
[DataContract]
public class CustomerInfo
{
private int customerId;
private string customerName, address, mobile, phone, email;
private DateTime birthdate;
[DataMember]
public int CustomerId
{
get
{
return customerId;
}
set
{
customerId = value;
}
}
[DataMember]
public stringCustomerName
{
get
{
return customerName;
}
set
{
customerName = value;
}
}
[DataMember]
public string Address
{
get
{
return address;
}
set
{
address = value;
}
}
[DataMember]
public string Mobile
{
get
{
return mobile;
}
set
{
mobile = value;
}
}
[DataMember]
public string Phone
{
get
{
return phone;
}
set
{
phone = value;
}
}
[DataMember]
public string Email
{
get
{
return email;
}
set
{
email = value;
}
}
[DataMember]
public DateTimeBirthdate
{
get
{
return birthdate;
}
set
{
birthdate = value;
}
}
}
Create & Configure the WCF Service Contract
using System.Net.Security;
using System.ServiceModel.Web;
[ServiceContract(Namespace = "http://test.example.net", ProtectionLevel = ProtectionLevel.None)]
public interface ICustomer
{
[OperationContract(ProtectionLevel = ProtectionLevel.None)]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetCustomer/{customer}")]
CustomerInfo GetCustomer(string customer);
}
Implement the WCF REST Service
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using System.Threading;
[ServiceBehavior(Namespace = "http://test.example.net", InstanceContextMode = InstanceContextMode.Single,
ConcurrencyMode = ConcurrencyMode.Multiple, AddressFilterMode = AddressFilterMode.Any)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Customer : ICustomer
{
private List<CustomerInfo> customers;
public Customer()
{
customers = new List<CustomerInfo>();
customers.Add(new CustomerInfo()
{
CustomerId = 3456,
CustomerName = "Muhammad",
Address = "any address",
Birthdate = DateTime.Now.AddYears(-20).Date,
Email = "Makhaly_cs@msn.com",
Mobile = "0123467890",
Phone = "53635363535"
});
customers.Add(new CustomerInfo()
{
CustomerId = 19008,
CustomerName = "Jone",
Address = "any address",
Birthdate = DateTime.Now.AddYears(-40).Date,
Email = "Jone@example.com",
Mobile = "0123467666890",
Phone = "53635363666535"
});
customers.Add(new CustomerInfo()
{
CustomerId = 56778,
CustomerName = "Henry",
Address = "any address",
Birthdate = DateTime.Now.AddYears(-34).Date,
Email = "Henry@example.com",
Mobile = "0123456785590",
Phone = "5363536553535"
});
customers.Add(new CustomerInfo()
{
CustomerId = 12233,
CustomerName = "Anthony",
Address = "any address",
Birthdate = DateTime.Now.AddYears(-28).Date,
Email = "Anthony@example.com",
Mobile = "012346557890",
Phone = "5363536553535"
});
customers.Add(new CustomerInfo()
{
CustomerId = 5677,
CustomerName = "Scott",
Address = "any address",
Birthdate = DateTime.Now.AddYears(-22).Date,
Email = "Scott@example.com",
Mobile = "0123469997890",
Phone = "53635363999535"
});
customers.Add(new CustomerInfo()
{
CustomerId = 433,
CustomerName = "Katrien",
Address = "any address",
Birthdate = DateTime.Now.AddYears(-30).Date,
Email = "Katrien@example.com",
Mobile = "0123469997890",
Phone = "53635363999535"
});
customers.Add(new CustomerInfo()
{
CustomerId = 2344,
CustomerName = "Julie",
Address = "any address",
Birthdate = DateTime.Now.AddYears(-35).Date,
Email = "Julie@example.com",
Mobile = "01234699887890",
Phone = "536353688763535"
});
}
[OperationBehavior]
public CustomerInfo GetCustomer(string customer)
{
try
{
Monitor.Enter(customers);
int customerId;
int.TryParse(customer, out customerId);
if (customers.Any(customerInfo => customerInfo.CustomerId == customerId))
{
CustomerInfo requiredCustomer = customers.Where(customerInfo =>
customerInfo.CustomerId == customerId).First();
return requiredCustomer;
}
else
{
throw new WebFaultException<string>("There is no customer with this Id.",
System.Net.HttpStatusCode.NoContent);
}
}
catch (Exceptionex)
{
throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.ServiceUnavailable);
}
finally
{
Monitor.Exit(customers);
}
}
}
Configure the WCF REST Service
<system.serviceModel>
<services>
<service name="WcfRestService.Customer" behaviorConfiguration="CustomerServiceBehavior">
<endpoint address="" binding="webHttpBinding" bindingConfiguration="webHttpBinding"
behaviorConfiguration="CustomerEndpointBehavior" contract="WcfRestService.ICustomer">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8732/Design_Time_Addresses/WcfRestService/Service1/"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="CustomerEndpointBehavior">
<webHttp automaticFormatSelectionEnabled="False" defaultBodyStyle="Bare"
defaultOutgoingResponseFormat="Json" faultExceptionEnabled="False" helpEnabled="False"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="CustomerServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="False" multipleSiteBindingsEnabled="True"/>
<bindings>
<webHttpBinding>
<binding name="webHttpBinding" closeTimeout="00:01:00" openTimeout="00:01:00"
receiveTimeout="00:02:00" sendTimeout="00:02:00" maxBufferSize="524288"
maxBufferPoolSize="524288" maxReceivedMessageSize="524288" writeEncoding="utf-8"
transferMode="Buffered">
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None" />
</security>
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
Publish the WCF REST Service
Host the WCF REST Service in IIS 7.5
Test the WCF REST Service
Now you have a WCF REST Service that returns specific HTTP Status Codes for specific situations such as where there is no data to return in a search query he want to return HTTP 204 No Content and HTTP 503 Service Unavailable when there is an unhandled exceptions.
15 March 2022
17 February 2022
09 December 2019