我有一个网络服务,我想从我的代码页面后面调用,而不是从我的源代码。我谷歌的主题,但在大多数链接中我发现他们通过使用ajax帖子从源代码调用Web服务
$.ajax({
type: "POST",
url: "webservice.asmx/webservice",
data: "{}",
contentType: "application/json; charset=utf-8",
cache: false,
dataType: "json",
success: function (result) {
}
});
但我不想使用这种方法我只想从我的代码behing页面调用webservice。有什么帮助吗?
答案 0 :(得分:5)
您可以使用此代码块。
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());
}
答案 1 :(得分:2)
您需要将Web Reference添加到项目中。
以下是有关如何使用网络服务的分步指南:
C#.Net How To: Consume a Web Service in C#.Net Visual Studio 2010