C# 不用添加WebService引用,調用WebService方法


  // 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消注釋以下行。 
  [System.Web.Script.Services.ScriptService]

使用HttpWebRequest 向WebService發送POST請求,並將請求頭:ContentType = "application/json;charset=utf-8",參數以JSON方式發送給WebService

/// <summary>
        /// 需要WebService支持Post調用
        /// </summary>
        public static string PostWebServiceByJson(String URL, String MethodName, Hashtable Pars)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);
            request.Method = "POST";
            request.ContentType = "application/json;charset=utf-8";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Timeout = 10000;
            byte[] data = Encoding.UTF8.GetBytes(HashtableToJson(Pars));
            request.ContentLength = data.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(data, 0, data.Length);
            writer.Close();
            
            StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8);
            String retXml = sr.ReadToEnd();
            sr.Close();
            return retXml;
        }
Hashtable ht = new Hashtable();
            ht.Add("LoginName", "Admin");
            ht.Add("Password", "Password");
            ht.Add("AppKey", "123");

            HttpHelper.PostWebServiceByJson("http://localhost/OpenApi/MobileService.asmx", "Login", ht);

WebService支持Post和Get方法

在Web.config添加下邊節點

<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>

 

參考

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM