1

我有一个 Web 服务,我想从页面后面的代码而不是源代码调用它。我在谷歌上搜索了这个主题,但在大多数链接中,我发现他们使用 ajax post 从源代码中调用了 Web 服务

 $.ajax({
            type: "POST",
            url: "webservice.asmx/webservice",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            cache: false,
            dataType: "json",
            success: function (result) {
            }
        }); 

但我不想使用这种方法,我只想从我的代码页面调用 web 服务。有什么帮助吗?

4

2 回答 2

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());

} 
于 2014-01-20T09:23:02.610 回答
2

您需要将 Web 引用添加到您的项目中。

以下是有关如何使用 Web 服务的分步指南:

C#.Net 操作方法:在 C#.Net Visual Studio 2010 中使用 Web 服务

于 2013-06-04T11:56:51.697 回答