Windows Communication Foundation (WCF) is an SDK for developing and
deploying services on Windows. WCF provides a runtime environment for our services, allow us to display CLR types as services, and to take other services as CLR types. In this post, I will to guide how to implement restful service API using WCF 4.0 in Visual Studio 2010 step by step.
Step 1: Launch Visual Studio 2010 and click on File->New-> Project. Then, select WCF in Visual C# tab and click on WCF Service Application.
Step 2: By default WCF service and interface file have been already created. Delete these files as we will create our own interface and WCF service file.
Step 3: Right click on Solution and create one new WCF service file, name it "WCFWebService.svc".
Step 4: Add the following code to "IWCFWebService.cs" file. This is an interface that enable the data to be returned. In this scenario, we will let the data return as XML format
[ServiceContract]
public interface IWCFWebService
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "xml/{id}")]
string XMLDoc(string id);
}
Step 5: Add the following code to "WCFWebserivce.cs" file:
public class WCFWebService : IWCFWebService
{
public string XMLDoc(string id)
{
return "Your requested product: " + id;
}
}
Step 6:
Finally, open the "web.config" file, there will be two basic sections of the configurations file that we must to know:
1. Service: This section contains information about the End Point. Modifying it as follow:
<system.serviceModel>
<services>
<service name="WCF.WCFWebService" behaviorConfiguration="WCFWebServiceBehaviour">
<endpoint address="" binding="webHttpBinding" contract="WCF.IWCFWebService" behaviorConfiguration="web">
</endpoint>
</service>
</services >
2. Behaviour: This section contains information about service and endpoint behavior. Modifying it as follow:
<behaviors>
<serviceBehaviors>
<behavior name="WCFWebServiceBehaviour">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
TEST THE SERVICE NOW
Right click on the file "WCFWebService.svc", the web service will display as follow:
Then, on the address bar, if we type the URL "http://localhost:59540/WCFWebService.svc/XML/A001", we get the following response on the browser in an XML format:
I hope that this post is useful for all of you!
0 comments:
Post a Comment