Creating WCF Rest API Get Method example.

This example shows you how to create wcf rest api for get method step by step.

Declare OperationContract and set WebInvoke properties to the method.

[OperationContract] [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, UriTemplate = "ServerTimeInJSON")] string ServerTimeInJSON();

In the above WebInvoke Properties

Method will be used to mention weather method is POST or GET

BodyStyle will be used to mention request and response can be wrapped or not

RequestFormat will be used to set the Request will be in format of XML or JSON

ResponseFormat will be used to set the Request will be in format of XML or JSON

UriTemplate will be used to set the URL to call the operation contract, it can be different from the OperationContract name.

Web.Config

Declare Service, end point under <system.serviceModel> section,

and end point behaviour under <system.serviceModel> -> <behaviors> section.

end point binding should be webHttpBinding and declare the endpoint behavior as webHttp.



<services> <service name="RestAPI.RestService" > <endpoint address="" binding="webHttpBinding" contract="RestAPI.IRestService" behaviorConfiguration="restbehavior" ></endpoint> </service> </services> <endpointBehaviors> <behavior name="restbehavior"> <webHttp /> </behavior> </endpointBehaviors>

Example

Service & Operation Contract Interface:

[ServiceContract] public interface IRestService { [OperationContract] [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, UriTemplate = "ServerTimeInJSON")] string ServerTimeInJSON(); [OperationContract] [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "ServerTimeInXML")] string ServerTimeInXML(); }

Interface Implementation:

public class RestService : IRestService { public string ServerTimeInJSON() { return DateTime.Now.ToString(); } public string ServerTimeInXML() { return DateTime.Now.ToString(); } }

And declare the web.config as discussed above.

Now you can run your first wcf rest api using get method.

you can download the source code form here... Download