繁体   English   中英

如何在背后调用Web服务表单代码

[英]How to call the web service form code behind

我有一个Web服务,我想从页面后面的代码而不是源代码中调用。 我用google搜索了这个主题,但是在大多数链接中,我发现它们使用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服务。 有什么帮助吗?

您可以使用此代码块。

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

} 

您需要将Web参考添加到您的项目。

这是有关如何使用Web服务的逐步指南:

C#.Net如何:在C#.Net Visual Studio 2010中使用Web服务

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM