.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

REST Web service,not getting response

Posted By:      Posted Date: September 23, 2010    Points: 0   Category :ASP.Net

Hi ,

I have to call a REST web service method that is deployed remotely on a machine and i use VPN to connect through that url. It works fine when i use the browser to view the output of the web service method but i am unable to get the response in the code as i get an exception. The response status message is OK but when i try to read the response content from the streamreader i get the exception "ex = {"Unable to read data from the transport connection: The connection was closed."}". The content length is -1 in the HttpWebReponse object. Here is the code

        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("");

        //apply this url when working with the software
       // HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:1901/metascan_rest/scanner?method=getengineinfo");
        request.Method = "GET";
        WebResponse res = request.GetResponse();

        string status = ((HttpWebResponse)res).StatusDescription;

        Stream stream = res.GetResponseStream();
        StreamReader reader = new StreamReader(stream);

          //this is where the exception occurs
            string output = reader.ReadToEnd();

View Complete Post

More Related Resource Links

Service Station: More On REST


This month's column answers frequently asked questions about implementing REST.

Jon Flanders

MSDN Magazine July 2009

Foundations: Build a Queued WCF Response Service


With queued calls in Windows Communication Foundation you can perform work in a disconnected manner by sending messages through Microsoft Message Queuing. Juval Lowy explains.

Juval Lowy

MSDN Magazine February 2007

Web Service that will receive xml request and send xml response


I am trying to create a web service that can do the following functionality:

Request XML 

<?xml version="1.0" encoding="UTF-8"?>
<Authentication UserName="test" Password="test" MyId="0987">

Response XML - After authenticating request xml from client send them back the following response:

<?xml version="1.0" encoding="UTF-8"?>
   <Test MyId="0987">
       <TestType id="11"></TestType>
       <TestType id="22"></TestType>

How can I create web service to do this.

Looking for a simple Service and Console Client REST sample implementing BASIC authentication


Does anyone know of a C# code sample demonstrating WCF REST services and console test client with OperationContracts (GET and POST) implementing mutiple paramaters using BASIC authentication? Also, perhaps, using Fiddler as a test client as well? I have searched high and low for something like this, but have not had any success.

Multiple services in REST Collection WCF Service?


After I create a "REST Collection WCF Service" project, it contains one service "service.svc". Can I add multiple services to this project? There must be a way to do so. Otherwise, it does not make sense to create one project for each service.


My question is how to add a new service to an existing "REST Collection WCF Service" project?


Thanks a lot.

Serializing Linq to Entities for use in a REST Service

What would be the best approach to send data retrieved from Linq to Entities over a rest service? For example, if you have a Linq to Entities class, say Products from the Northwind database. I want to return a subset of the Products (based on a query on the model) back through a service. First a retrieve a List<Product> from the context, and then i need to serialize the data and send it over the wire. If I use the exact Linq to Entities class, then there is so much "garbage" that it either fails outright (from a circular reference) or you are wasting bandwith. What is a design to overcome this? Create POCO objects for each linq to entities class you want to send and create custom code to tranform each object in the list to the POCO object? This is the only way I can see doing it, although it would be very tedius to create and maintain (unless some custom code generation was created). Is there a better approach? clients

System.ComponentModel.DescriptionAttribute not showing up in REST service

I am trying to set the description for a REST WCF service, but it doesn't seem to be working. Code is: [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]     [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]     [WebDispatchFormatterConfiguration("application/xml")]     [WebDispatchFormatterMimeType(typeof(WcfRestContrib.ServiceModel.Dispatcher.Formatters.PoxDataContract), "application/xml", "text/xml")]     [WebDispatchFormatterMimeType(typeof(WcfRestContrib.ServiceModel.Dispatcher.Formatters.DataContractJson), "application/json")]     [WebDispatchFormatterMimeType(typeof(WcfRestContrib.ServiceModel.Dispatcher.Formatters.FormUrlEncoded), "application/x-www-form-urlencoded")]     public class PublicAppointmentSchedulerSvc : IPublicAppointmentScheduler     {         IPublicAppointmentScheduler impl = new PublicAppointmentScheduler();         [WebDispatchFormatter]         [Description("Immediate or callback contact request")]         [WebInvoke(UriTemplate = "InitiateContact", Method = Verbs.Post)]  &n

Post the SAML Response in an HTML form to the assertion consumer service

Hi,   Can anyoner please help me in how to post the SAML Response in an HTML form to the assertion consumer service. I have generated the saml reponse and want to send the same to the re-directing url.  

GoDaddy + WCF REST Service

I am newbie when it comes to developing a WCF REST Service. I have been reading up and have worked through hands-on labs/watched videos by Ron Jacobs to help me get a hold of WCF REST.  I have had no problems running my web service on my localhost. However it is now time to upload my "WCF Service Application" (not WCF Library) to GoDaddy's servers and this is where I am running into issues. As per Ron Jacobs tutorials I have removed my endpoints from my web.config file and the markup code in my .svc file now reads: <%@ ServiceHost Language="C#" Debug="true" Service="DealService.Service" CodeBehind="Service.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory"%> I proceeded to compile and then upload my code to GoDaddy and now am trying to access the web service, but am receiving the following error: Server Error in '/' Application. Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.  Parser Error Message: The CLR Type 'System.ServiceModel.Activation.WebServiceHostFactory' could not be loaded during service compilation. Verify that this type is either defined in a source file located in the application's \App

ASP.Net Client for Php REST Service

 I am writing some code in an asp application that needs to communicate with a PHP REST Service. I have 2 questions. 1.  In my data variable I have to put the POST parameters.  If I needed to put reserved characters like & or ? into the string is there an escape character I can use?  Or would encoding it work?  Or would it totally depend on how the web service works? 2.  Is the code I am using the usual way to make a POST connection to a REST service?  Or is there an easier/faster way? Below is the code I am using Dim uri As New Uri("http://help.domain.com/api/index.php?method=request.create") Dim data As String = "tNote=Testing Code&sEmail=test@test.com" If uri.Scheme = uri.UriSchemeHttp Then Dim request As HttpWebRequest = HttpWebRequest.Create(uri) request.Method = WebRequestMethods.Http.Post request.ContentLength = data.Length request.ContentType = "application/x-www-form-urlencoded" Dim writer As New StreamWriter(request.GetRequestStream) writer.Write(data) writer.Close() Dim oResponse As HttpWebResponse = request.GetResponse() Dim reader As New StreamReader(oResponse.GetResponseStream()) Dim tmp As String = reader.ReadToEnd() oResponse.Close()

PUT method gives error 400 "Bad Request" in WCF REST Service Application

I am trying to learn WCF REST Services through http://blogs.msdn.com/endpoint/archive/2010/01/14/updating-state-in-wcf-webhttp-services.aspx , It's a link of Part 3 of 12 part blog series. Now I am trying the same stuff given in the part 3 with my own Entities and Entity Model instead of what is given in the blog. Here is my full project I am working on .. http://cid-9e3f62c0688824b0.skydrive.live.com/self.aspx/.Public/pronerveEPMS.zip For comparision with the code shown in the Blog I am following, you can download the zip file of the project from the same link given here at starting (At the end of the blog and before comments starts). And here is the method in Program.cs file of console project in my application that raises the exception.....        private static Role UpdateRole(HttpClient hc, Role role1)        {            Console.WriteLine("Updating Role {0} : ",     role1.RoleID);            Console.WriteLine();            string updateURI = "Roles/" + role1.RoleID.ToString();            HttpContent content = HttpContentExtensions.CreateDataContract(role1);            using (HttpResponseMessage response = hc.Put(upd

How to remove .svc from URL in REST service with WCF 3.5 on IIS 7

Hi, I'm using REST WCF3.5 with JSON as output. My URL to delete person info is http://localhost/RestService/RestService.svc/myproject/persons/3  I'm using IIS7 in Windows Server 2008. How do I get rid of .svc extension in the URL so that client can use URL like http://localhost/RestService/myproject/persons/3 ? Thanks!

creating a sample web service response

I am trying to simulate a sample web service payload similar to that which i will receive one the webservice is live. Can anyone help me simulate this?Criteria for my response will be:a bool pass or failstring - messageand the object (in this case in the form of a list)heres the class I am to populate with sample data: public class WebServiceCollectionResponse { private List<Object> _returnObjects; public bool Success { get; set; } public string Message { get; set; } public List<Object> ReturnObjects { get { if (_returnObjects != null) return _returnObjects; else return new List<object>(); } set { _returnObjects = value; } } } How can I use this class to put sample data in it? Lets say I want to put customers in the list 'ReturnObjects'?Thanks for your time.

host and consume wcf rest service in web project in single solution

I have  create a solution which have multiple class library project and a web application Like Web(UI),BL,DAL etc. I have also add a WCF REST starter kit Collection project in the same Solution.WCF Rest API is working fine if I host it on IIS but i want to consume this in my web project without using IIS. Is this possible? if yes then what will be the URI  for my WCF Rest services? Add service reference is also not working because WSDL is disable in rest.

Infopath 2010 cannot connect to Rest web service

Hi all, I recently tried to access an Excel spreadsheet range as a Rest web service in Infopath 2010; no luck.  Here are the steps I followed: 1. [Successful] Upload Excel spreadsheet with the said ranges onto a Sharepoint document library 2. [Successful] Bind the Excel spreadsheet range (I have one called Regions) in the Sharepoint document library as a Rest web service in Infopath form's listbox control during design time as follows - http://mosscrm/sites/sandbox/_vti_bin/excelrest.aspx/eventbudgets/lookups.xlsx/model/ranges('Regions')?$format=atom 3. [Failed] Then I tried to preview the form, but the actual data in the Excel range failed to populate the Infopath listbox control.  The error I got was: "Could not open "http://<localhost>/sites/<site name>/_vti_bin/ExcelRest.aspx/EventBudgets/Lookups.xlsx/Model/Ranges('EventTypes')?$format=atom"   The error I then got from Infopath was a pop-up saying: The query cannot be run for the following DataObject: Event Types InfoPath cannot run the specified query. The file is not a valid XML file. Not enough storage is available to process this command . If anyone out there has experienced a similar issue and resolved it, please kindly share your solution approach. Thanks.

null response when consume WCF REST API Using Jquery

I have created and hosted my WCF REST API Using WCF REST Starter Kit preview2. Which supports Dynamic Response and Request format type (XML and JSON).Everything is working fine if I consume the service through fiddler or Microsoft.Http and Microsoft.Http.Extensions on cs side. My cs code is as following: private void GetData() { string url = string.Format("http://myhost/Services/UserService.svc/people/"); HttpClient client = new HttpClient(); HttpResponseMessage responseMessage = client.Get(url); responseMessage.EnsureStatusIsSuccessful(); using (responseMessage) { string res = responseMessage.Content.ReadAsString(); Response.Write(res); } } now when I try to consume my service using Jquery Response is comming in IE8 but in Mozilla and Chrome I am getting null response My jquery code is as following : function loadData() { var path = "http://myhost/Services/UserService.svc/people/"; $.ajax({ type: "GET", url: path, contentType: "application/json; charset=utf-8", dataType: "json", async: false, success: function(response) { if (response != null) { displayData(response); } } }); } I am using visual studio 2008. I have also check jqeury call in firebug status shows 200 OK. can anyone help me?

How WCF 4 REST Service Support Form Post As Well As XML and JSON?


Using the rest 4 template.  I have a POST method defined, with an object as a parameter.  REST 4 does a great job of automatically mapping both xml and json posts to the method.  I tested this using an HttpClient test application to build and post xml content and then json content. 

I want to also support a standard form post to the method but am having problems!  

I'd like the same method already accepting and converting both xml and json to also work correctly for a form post.  I am testing this by creating an HttpUrlEncoded form in the test client, adding form name/value pairs that match what the method is expecting, and trying to post it.

However I get a 400 Bad Request.  Here's some example code that is returning a 400 bad request:

            var client = new HttpClient();

            HttpUrlEncodedForm form = new HttpUrlEncodedForm();
            form.Add("Id", "99");
            form.Add("Message", "Message test with 'special' chars #!#");
            form.Add("IpAddress", "");

            var response = client.Post("<valid-uri-here>", form.CreateHttpContent());

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend