Reputation: 51
I have one web service which I want to call from my code behind page not from my source code. I google the topic but in most of the links I found that they called the web service from the source code by using ajax post
$.ajax({
type: "POST",
url: "webservice.asmx/webservice",
data: "{}",
contentType: "application/json; charset=utf-8",
cache: false,
dataType: "json",
success: function (result) {
}
});
But I don't want to use this approach I simply want to call the webservice from my code behing page. Any help?
Upvotes: 1
Views: 16222
Reputation: 2095
You need to add Web Reference to your project.
Here is a step by step guide on how to consume a web service :
C#.Net How To: Consume a Web Service in C#.Net Visual Studio 2010
Upvotes: 2
Reputation: 677
You can use this code block.
public string CallWebMethod(string url, Dictionary<string, string> dicParameters)
{
try
{
byte[] requestData = this.CreateHttpRequestData(dicParameters);
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.KeepAlive = false;
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.ContentLength = requestData.Length;
httpRequest.Timeout = 30000;
HttpWebResponse httpResponse = null;
String response = String.Empty;
httpRequest.GetRequestStream().Write(requestData, 0, requestData.Length);
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream baseStream = httpResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(baseStream);
response = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
return response;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private byte[] CreateHttpRequestData(Dictionary<string, string> dic)
{
StringBuilder sbParameters = new StringBuilder();
foreach (string param in dic.Keys)
{
sbParameters.Append(param);//key => parameter name
sbParameters.Append('=');
sbParameters.Append(dic[param]);//key value
sbParameters.Append('&');
}
sbParameters.Remove(sbParameters.Length - 1, 1);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(sbParameters.ToString());
}
Upvotes: 5