Tuesday, December 3, 2013

Call/Invoke or consume webservice with parameter


Create a method in your webservice

[WebMethod]
    public void Save(string id,string Name,string Age,string Mob) {

        SqlCommand cmd = new SqlCommand();
      
        cmd.Parameters.AddWithValue("@ID", id)
        cmd.Parameters.AddWithValue("@name", Name);
        cmd.Parameters.AddWithValue("@age", Age);
        cmd.Parameters.AddWithValue("@mob", Mob);
                cmd.CommandText = "Pro_SaveData";
        cmd.CommandType = CommandType.StoredProcedure;
        ExecuteNonQuery(cmd);
    }
Call the webservice in your code behind

        string id = txtid.text;       
string Name = txtname.text;
        string age = txtage.text;
        string mob = txtmob.text;
        string URLAuth = "http://localhost/wsSave.asmx/Save";
        string postString = string.Format("id=" + id + "&Name=" + Name + "&age=" + age + "&mob=" + mob);

        const string contentType = "application/x-www-form-urlencoded";
        System.Net.ServicePointManager.Expect100Continue = false;

        CookieContainer cookies = new CookieContainer();
        HttpWebRequest webRequest = WebRequest.Create(URLAuth) as HttpWebRequest;
        webRequest.Method = "POST";
        webRequest.ContentType = contentType;
        webRequest.CookieContainer = cookies;
        webRequest.ContentLength = postString.Length;
        webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1";
        webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

        StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
        requestWriter.Write(postString);
        requestWriter.Close();

        StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
        string responseData = responseReader.ReadToEnd();

        responseReader.Close();
        webRequest.GetResponse().Close();

No comments:

Post a Comment