Introduction
In this article, we will see how to create WCF REST based service. In this example, we will define two methods,GetSampleMethod (method type is GET) & PostSampleMethod (method type is POST). GETmethod will take input asString& returns formattedString.POSTmethod will take input as XML (user registration) & return statusstring.
webHttpBinding. We will divide this article into the below sections:
- Define WCF Service
- Define Interface
- Define Class
- Implement
POST&GETmethods - Define Configuration for WCF Service
- Service Configuration
- Behavior Configuration
- Smoke test WCF service (before client uses it)
- Implement client code to use WCF service
Define WCF Service
- Open VS 2010 & Select new Project, then select WCF & select WCF Service Application & name it as WCF Rest Based.
- Now add new
Serviceclass to this application as “MyService.svc” - Open interface IMservice.cs & add the below code:
OperationContract:PostSampleMethodWebInvokeMethod Type =POSTas we are implementingPOST- URI Template defines the URL format by which this method is identified / linked.
Note: MethodName, URI Template name & Operation Contract names may not be same means they can be different PostSampleMethodwill accept XMLstringas input inPOSTmethod. UsingStreamas input parameter, we can de-serialize input data before using it.
[OperationContract(Name = “PostSampleMethod”)]
[WebInvoke(Method = “POST”,
UriTemplate = “PostSampleMethod/New”)]
string PostSampleMethod(Stream data);
}OperationContractname:GetSampleMethodWebGetattribute defined method type isGET- Need to include below namespaces:
System.ServiceModel
System.Runtime.Serialization
System.IO
[OperationContract(Name = “GetSampleMethod”)]
[WebGet(UriTemplate = “GetSampleMethod/inputStr/{name}”)]
string GetSampleMethod(string name); - Open MyService.cs class and provide implementation for the methods defined in
IMyServiceInterface as shown below:
System.ServiceModel.Web;
public string PostSampleMethod(Stream data)
{
// convert Stream Data to StreamReader
StreamReader reader = new StreamReader(data);
// Read StreamReader data as string
string xmlString = reader.ReadToEnd();
string returnValue = xmlString;
// return the XMLString data
return returnValue;
}
public string GetSampleMethod(string strUserName)
{
StringBuilder strReturnValue = new StringBuilder();
// return username prefixed as shown below
strReturnValue.Append(string.Format
(”You have entered userName as {0}”, strUserName));
return strReturnValue.ToString();
}
Define Configuration for WCF Service
- Open web.config as we need to define configuration for our WCF Service. If you want our service to be accessed as part of
webHttp, then we need to definewebHttpBinding&mexHttpBinding. - In
System.ServiceModeldefined configuration as shown below. To know details about the below config configuration, check out the URL: https://ch1blogs.cognizant.com/blogs/279850/2011/10/18/service-end-point-not-found/.
<services>
<service name=”WcfRestBased.MyService”
behaviorConfiguration=”myServiceBehavior” >
<endpoint name=”webHttpBinding”
address=”"
binding=”webHttpBinding”
contract=”WcfRestBased.IMyService”
behaviorConfiguration=”webHttp”
>
</endpoint>
<endpoint name=”mexHttpBinding”
address=”mex”
binding=”mexHttpBinding”
contract=”IMetadataExchange”
/>
</service>
</services>
Service Name: To find what's to be given, right click the service & selectViewMarkupoption.
Example, in my case, it is MyService.svc, look forServiceattribute & use the completestring, in my case it isService=”WcfRestBased.MyService”.
behaviorConfiguration: can be any name but this will be again used when we define behavior settings, in my case it ismyServiceBehavior.
Endpoint for webHttpBinding
- endpoint name: should be
webHttpBindingif you are configuring for web access - address: we can leave it empty
- binding: should be
webHttpBinding - contract: should be
Namespace.Interfacename. In my case, it iswcfRestBased.IMyService - behaviorConfiguration: should be
webHttp
EndPoint for mexHttpBinding
These values should be same as shown above.3. Now define Service behavior as shown below in
System.ServiceModel. “mySeriveBehavior” name should match behaviorConfiguration name defined in Service tag (shown above):
<behaviors>
<serviceBehaviors>
<behavior name=”myServiceBehavior” >
<serviceMetadata httpGetEnabled=”true”/>
<serviceDebug includeExceptionDetailInFaults=”false” />
</behavior>
<behavior>
<!– 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=”false”/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name=”webHttp”>
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceBehaviors>
<behavior name=”myServiceBehavior” >
<serviceMetadata httpGetEnabled=”true”/>
<serviceDebug includeExceptionDetailInFaults=”false” />
</behavior>
<behavior>
<!– 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=”false”/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name=”webHttp”>
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
Smoke Test WCF Service
- Configure WCF Service in IIS
- To check our WCF service is working properly, let's test it by opening MyService.svc in browser, in my case it is http://localhost/wcfrestbased/MyService.svc
- To test our
GETmethod service, you can call it by http://localhost/wcfrestbased/MyService.svc/GetSampleMethod/inputStr/suryaprakash & this shows up data as “You have entereduserNameassuryaprakash”. - By this, we can confirm our service is working fine.
Implement Client Code to Use WCF Service
- Create new website application which will act as client to access WCF services.
- Add a
textboxto default.aspx page & name it astxtResult& open Default.aspx.cs - Define below function which will call rest service to fetch the data. This method will call
POSTSAMPLEMETHODin service (MyService) implemented. Inline code comments are added.
void CallPostMethod()
{
// Restful service URL
string url =
“http://localhost/wcfrestbased/myservice.svc/PostSampleMethod/New“;
// declare ascii encoding
ASCIIEncoding encoding = new ASCIIEncoding();
string strResult = string.Empty;
// sample xml sent to Service & this data is sent in POST
string SampleXml = @”<parent>” +
“<child>” +
“<username>username</username>” +
“<password>password</password>” +
“</child>” +
“</parent>”;
string postData = SampleXml.ToString();
// convert xmlstring to byte using ascii encoding
byte[] data = encoding.GetBytes(postData);
// declare httpwebrequet wrt url defined above
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
// set method as post
webrequest.Method = “POST”;
// set content type
webrequest.ContentType = “application/x-www-form-urlencoded”;
// set content length
webrequest.ContentLength = data.Length;
// get stream data out of webrequest object
Stream newStream = webrequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
// declare & read response from service
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
// set utf8 encoding
Encoding enc = System.Text.Encoding.GetEncoding(”utf-8?);
// read response stream from response object
StreamReader loResponseStream =
new StreamReader(webresponse.GetResponseStream(), enc);
// read string from stream data
strResult = loResponseStream.ReadToEnd();
// close the stream object
loResponseStream.Close();
// close the response object
webresponse.Close();
// below steps remove unwanted data from response string
strResult = strResult.Replace(”</string>”, “”);
strResult = strResult.Substring(strResult.LastIndexOf(’> - Now let's go ahead and implement code to call
GETSAMPLEMETHODfrom client application. The below code has inline comments:
void CallGetMethod()
{
// Restful service URL
string url = “http://localhost/wcfrestbased/myservice.svc/
GetSampleMethod/inputStr/suryaprakash“;
string strResult = string.Empty;
// declare httpwebrequet wrt url defined above
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
// set method as post
webrequest.Method = “GET”;
// set content type
webrequest.ContentType = “application/x-www-form-urlencoded”;
// declare & read response from service
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
// set utf8 encoding
Encoding enc = System.Text.Encoding.GetEncoding(”utf-8?);
// read response stream from response object
StreamReader loResponseStream = new StreamReader
(webresponse.GetResponseStream(), enc);
// read string from stream data
strResult = loResponseStream.ReadToEnd();
// close the stream object
loResponseStream.Close();
// close the response object
webresponse.Close();
// assign the final result to text box
txtResult.Text = strResult;
} - Now go ahead and call the above methods to see the output of each method.
codeproject.com


10:42 AM
Unknown
Posted in:
1 comments:
it's useful
Post a Comment