Saturday 28 May 2016

calling web service without adding web reference


Introduction:

Here I will explain how to calling web service without adding web reference using C# code using. Sometimes required to call particular web service without adding web reference at that time we need to call that web service using WebRequest. Once we created and deployed web service that time client required to call webservice so how to do this.

So, Now I explaining how to call web service without adding web reference.


Description: 

In previously post I explained to  
file type validation in jquery
Change the column name or datatype or size in sql server
How to set or get textbox value using Javascript or Jquery
Server does not support secure connections  
Three tier architecture in asp.net
Remove .aspx from url in asp.net

And now here I explain to how to call web service without adding web reference using C# code.

Now copy the following code in your page.

this is the method in MyWebService.asmx wants to call without adding web reference
 


    [WebMethod]
    public string MyDemoWebService(string data1, string data2)
    {
       // Your code here

       return "";

    }


 Now copy the following code in code behind where you want to call web service.

private string CallWebService(string data1, string data2)
    {
        if (Request.IsLocal)
        {

        }
        string result = "";
        string strPost = "data1=" + data1+ "&data2=" + data2;
        StreamWriter myWriter = null;
        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
        objRequest.Method = "POST";
        objRequest.Timeout = 200000; // this should be greater than IIS / web server's timeout
        objRequest.ContentLength = strPost.Length;
        objRequest.ContentType = "application/x-www-form-urlencoded";
        objRequest.KeepAlive = false;
        try
        {
            myWriter = new StreamWriter(objRequest.GetRequestStream());
            myWriter.Write(strPost);

        }
        catch (Exception e)
        {
            throw new Exception(e.ToString());
        }
        finally
        {
            myWriter.Close();
        }
        HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
        using (StreamReader sr = new StreamReader(objResponse.GetResponseStream)))
        {
            result = sr.ReadToEnd();
            sr.Close();
        }
        return result;
    }
 


  Now call above function CallWebService in your button click event with given parameter and your web service is called without adding web reference. you will get response in result string variavle.

Now run your project and check.

 

 

2 comments:

  1. Sir, this line,
    HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); its throwing error that "The remote server returned an error: (500) internal server error.

    ReplyDelete
  2. Its working very fine thak you so much!

    ReplyDelete



Asp.net tutorials