Interaction between WebRequest and WebMethods

VS2010, C #,. NET 4

I created 2 apps: a web service and a windows forms app (both running on the same pc). Here is the code:

WEBSERVICE:

public class Service1 : System.Web.Services.WebService
{

    [WebMethod]
    public string HelloWorld()
    {
        return "message";
    }
}

      

APPLICATION WINDOWS:

HttpWebRequest req =(HttpWebRequest)WebRequest.Create("http://localhost:20848/Service1.asmx/HelloWorld");

req.Credentials = CredentialCache.DefaultCredentials;
req.Method = "POST";                
//Set the content type of the data being posted.
req.ContentType = "application/text";

WebResponse res = req.GetResponse();

StreamReader sr = new StreamReader(res.GetResponseStream());
string txtOutput = sr.ReadToEnd();
Console.WriteLine(sr.ReadToEnd());

      

THIS ONLY WORKS THROUGH. I am getting a response from webservice that contains a message. Now I change apps 2 apps to this:

WEB SERVICE:

public class Service1 : System.Web.Services.WebService
{

    [WebMethod]
    public string HelloWorld(string message)
    {
        return message;
    }
}

      

APPLICATION WINDOW FOR FORMS:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:20848/Service1.asmx/HelloWorld");

req.Credentials = CredentialCache.DefaultCredentials;
req.Method = "POST";
string inputData = "sample webservice";
string postData = "message=" + inputData;

byte[] byte1 = System.Text.ASCIIEncoding.ASCII.GetBytes(postData);
req.ContentLength = byte1.Length;
Stream postdataStream = req.GetRequestStream();

//Set the content type of the data being posted.
req.ContentType = "application/text";

postdataStream.Write(byte1, 0, byte1.Length);

WebResponse res = req.GetResponse();

StreamReader sr = new StreamReader(res.GetResponseStream());
string txtOutput = sr.ReadToEnd();
Console.WriteLine(sr.ReadToEnd());

      

THIS IS A MALFUNCTION IN req.GetResponse (); "It says the underlying connection is closed." Can someone tell me what is wrong with the code here. Note. I MUST only access WebMethods using WebRequests. I don't want to add a web link.

+3


source to share


1 answer


, , GetResponse(). , docs . , .

..



postdataStream.Write(byte1, 0, byte1.Length);
postDataStream.Close();
WebResponse res = req.GetResponse();

      

0









All Articles