Solved

Calling a RESTful WCF Service

Posted on 2011-03-15
6
1,747 Views
Last Modified: 2012-06-27
Dear Experts,

I am trying to invoke a RESTful WCF service programmatically.

This is the OperationContract method.

 [WebInvoke(Method = "POST", UriTemplate = "submitPaymentToBankURI")]
[OperationContract]
Stream submitPaymentToBank(Stream info);

This is the client code:

 string baseAddress = "http://localhost:1287/CreditCardWebServiceRESTSite/CreditCardServiceREST.svc";

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(baseAddress + "/submitPaymentToBankURI");
            req.Method = "POST";
            req.ContentType = "text/plain";

            Stream reqStream = req.GetRequestStream();
            string inputData = "MyData";
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] DataToSend = encoding.GetBytes(inputData);
            reqStream.Write(DataToSend, 0, DataToSend.Length);
            reqStream.Close();
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Console.WriteLine("Client: Receive Response HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);

            StreamReader loResponseStream = new StreamReader(resp.GetResponseStream(), encoding);
            string lcHtml = loResponseStream.ReadToEnd();
            Console.WriteLine(lcHtml);
            Console.ReadLine();

I am using WebHttpBinding.

I am getting an exception on this line:
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

Exception Details:
System.Net.WebException was unhandled
  Message="The remote server returned an error: (400) Bad Request."
  Source="System"
  StackTrace:
       at System.Net.HttpWebRequest.GetResponse()
       at TestCreditCardWebServiceREST.Program.Main(String[] args) in C:\MyProject\TestCreditCardWebServiceREST\Program.cs:line 61
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

Any clues on how to fix this?

Thanks in advance for your help.
0
Comment
Question by:shekhar_shashi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
6 Comments
 
LVL 18

Accepted Solution

by:
DarrenD earned 500 total points
ID: 35149800
0
 
LVL 3

Author Comment

by:shekhar_shashi
ID: 35151233
Hi Darren,

Yes, I have tried this link before. I can get the my code (and also the code in the link) to work with HTTP Get but not with Post.

Thanks
0
 
LVL 18

Assisted Solution

by:DarrenD
DarrenD earned 500 total points
ID: 35160706
Hi,

How about this?

[OperationContract]
    [WebInvoke
        (Method = "POST",
        RequestFormat = WebMessageFormat.Xml,
        UriTemplate = "/SetGasPrice/For/ZipCode/{zipCode}/Price/{price}"
        )]
    void SetPriceDataForZipCode(string zipCode, string price);
}

Got this from here:
http://stackoverflow.com/questions/385451/wcf-restful-post-question

Cheers,

Darren
0
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 
LVL 3

Assisted Solution

by:shekhar_shashi
shekhar_shashi earned 0 total points
ID: 35183189
Hi Darren,

I managed to fix the issue by doing the following:

1. Removed old code and started from scratch.
2. Created WCF Library and added a new service and the same method.
The method signature is:

[WebInvoke(Method = "POST", UriTemplate = "submitPayment", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
        [OperationContract]
        Stream submitPaymentToBank(Stream info);

3. Made sure I exposed an endpoint with WebHttpBinding binding. Also I added an endpoint behavior that used webHttp behavior.

Config file is:

<system.serviceModel>
    <services>
      <service behaviorConfiguration="CreditCardWebServiceREST.CreditCardWebServiceRESTBehavior"
        name="CreditCardWebServiceREST.CreditCardWebServiceREST">
        <clear />
        <endpoint behaviorConfiguration="WebBehavior" binding="webHttpBinding"
          bindingConfiguration="" contract="CreditCardWebServiceREST.ICreditCardWebServiceREST"
          listenUriMode="Explicit" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"
          listenUriMode="Explicit" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:2524/CreditCardWebServiceREST/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="WebBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="CreditCardWebServiceREST.CreditCardWebServiceRESTBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
 
4. I added a new WCF website that uses the WCF library. This is a pre-compiled site that has a service file with this code.

<%@ ServiceHost Service="CatalogWebServiceREST.CatalogWebServiceREST"
Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>

Also - both projects have a reference to System.ServiceModel.Web.


5. This is my client code.


  string baseAddress = "http://localhost:xxxx/CreditCardService.svc";

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(baseAddress + "/submitPayment/");
            req.Method = "POST";
            req.ContentType = "text/plain";

            Stream reqStream = req.GetRequestStream();
            string inputData = "MyData";
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] DataToSend = encoding.GetBytes(inputData);
            reqStream.Write(DataToSend, 0, DataToSend.Length);
            reqStream.Close();
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Console.WriteLine("Client: Receive Response HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);

            StreamReader loResponseStream = new StreamReader(resp.GetResponseStream(), encoding);
            string lcHtml = loResponseStream.ReadToEnd();
            Console.WriteLine(lcHtml);
            Console.ReadLine();


This code is stolen from:
http://www.west-wind.com/presentations/dotnetwebrequest/dotnetwebrequest.htm

Everything works like a charm!!!


0
 
LVL 3

Author Comment

by:shekhar_shashi
ID: 35183204
Hi Darren,

Thanks for the all the research work. You deserve full points and so I'll award points shortly.

0
 
LVL 3

Author Closing Comment

by:shekhar_shashi
ID: 35221232
Thanks
0

Featured Post

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

No security measures warrant 100% as a "silver bullet". The truth is we also cannot assume anything but a defensive and vigilance posture. Adopt no trust by default and reveal in assumption. Only assume anonymity or invisibility in the reverse. Safe…
Article by: btan
The intent is not to repeat what many has know about Ransomware but more to join its dots of what is it, who are the victims, why it exists, when and how we respond on infection. Lastly, sum up in a glance to share such information with more to help…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Suggested Courses

626 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question