Академический Документы
Профессиональный Документы
Культура Документы
POST Methods
Bangla Gopal Surya Prakash, 30 Oct 2011
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).
GET method will take input as String & returns formatted String.
POST method will take input as XML (user registration) & return status string.
Note: One should have basic knowledge of what is WCF, why WCF & my article will discuss HOW to
use WCF with webHttpBinding.
4. Open MyService.cs class and provide implementation for the methods defined
in IMyService Interface as shown below:
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 & select ViewMarkup option.
Example, in my case, it is MyService.svc, look for Service attribute & use the complete string, in
my case it is Service=”WcfRestBased.MyService” .
behaviorConfiguration: can be any name but this will be again used when we define behavior
settings, in my case it is myServiceBehavior.
o endpoint name: should be webHttpBinding if you are configuring for web access
o address: we can leave it empty
o binding: should be webHttpBinding
o contract: should be Namespace.Interfacename. In my case, it is wcfRestBased.IMyService
o behaviorConfiguration: should be webHttp
set the value below to false and remove the metadata endpoint
4. Now let's go ahead and implement code to call GETSAMPLEMETHOD from client application. The
below code has inline comments:
Hide Copy Code
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;
}
5. Now go ahead and call the above methods to see the output of each method.