How to call webservices with ASP.NET at Run time?

來源:互聯網
上載者:User

1. 一般情況下,我們都用HttpWebRequest來調用WebServices.

建立WebServices:

代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Runtime.Serialization;

/// <summary>
/// Summary description for CustomerWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
[ScriptService]
public class CustomerWebService : System.Web.Services.WebService
{
    public CustomerWebService()
    {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    //[WebMethod]
    //public string HelloWorld() {
    //    return "Hello World";
    //}
    [ScriptMethod]
    [WebMethod]
    public string Register(long id, string data1)
    {
        return "ID.CUSTOMER";
    }
    [ScriptMethod]
    [WebMethod]
    public string HelloWorld(Person p)
    {
        return p.Name;
    }
}
[DataContract]
public class Person
{
    [DataMember]
    public string Name { get; set; }
}

 

在IE中輸入webservices地址(http://localhost:8485/MySite/CustomerWebService.asmx?op=HelloWorld),可看到調用該services的soap訊息格式.

代碼

POST /MySite/CustomerWebService.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/HelloWorld"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <HelloWorld xmlns="http://tempuri.org/">
      <p>
        <Name>string</Name>
      </p>
    </HelloWorld>
  </soap:Body>
</soap:Envelope>

 

2.調用webServices

 

代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Text;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(OnValidationCallback);
        try
        {
            //string param = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
            StringBuilder strb = new StringBuilder();
            strb.Append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
  strb.Append("<soap:Body>");
    strb.Append("<HelloWorld xmlns=\"http://tempuri.org/\">");
      strb.Append("<p>");
        strb.Append("<Name>Personss</Name>");
      strb.Append("</p>");
    strb.Append("</HelloWorld>");
  strb.Append("</soap:Body>");
strb.Append("</soap:Envelope>");
            string param=strb.ToString();
            byte[] bs = Encoding.UTF8.GetBytes(param);
            HttpWebRequest myRequest =
                (HttpWebRequest)WebRequest.Create(
                "http://localhost:8485/MySite/CustomerWebService.asmx");
            myRequest.Method = "POST";
            myRequest.ContentType = "text/xml; charset=utf-8";
            myRequest.Headers.Add("SOAPAction", "http://tempuri.org/HelloWorld");
            myRequest.ContentLength = bs.Length;
            using (Stream reqStream = myRequest.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
            }
            using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
            {

                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string responseString = sr.ReadToEnd();
                Response.Write("結果:" + responseString);
            }
        }
        catch (Exception ex)
        {
            Response.Write(System.DateTime.Now.ToShortTimeString()
                + "LBS EXCEPTION:" + ex.Message);
            Response.Write(ex.StackTrace);
        }
    }
    public bool OnValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
    {
        return true;
    }

}

 

如果出現500內部伺服器錯誤:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(OnValidationCallback);
 public bool OnValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
    {
        return true;
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.