天天看點

一起談.NET技術,SilverLight調用WebService的方法

  在我們添加Service Reference的時候,可能不知道該服務最終會被部署到什麼位置,或者該服務可能被遷移,此時我們可以使用以下手段進行Service的調用,提高代碼編寫的靈活性。

  步驟1:修改宿主Web頁面的代碼,将服務位址以初始化參數方式傳入。

<form id="form1" runat="server" style="height:100%">

    <div id="silverlightControlHost">

        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">

          ...

          <param name="InitParams" value="serviceAddress=http://localhost/services/myservices.asmx" />

          <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration:none">

               <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style:none"/>

          </a>

        </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>

    </form>

  步驟2:添加Service引用并注冊調用遠端方法的事件處理。

  添加Service的引用不必贅述.但此處添加Service Reference的目的僅在于獲得遠端方法的命名空間等程式結構資訊。

  如果我們的Silverlight程式首頁面名叫MainPage,則在MainPage.xaml.cs中添加如下代碼:

       public void InitializeServices(string serviceAddress)

        {

            BasicHttpBinding basicBinding = new BasicHttpBinding();

            CustomBinding binding = new CustomBinding(basicBinding);

            BindingElement binaryElement = new BinaryMessageEncodingBindingElement();

            EndpointAddress endPoint = new EndpointAddress(serviceAddress);

            MyService.MyServicesSoapClient serviceClient = (MyServicesSoapClient)Activator.CreateInstance(typeof(MyServicesSoapClient), binding, endPoint);

            serviceClient.MyRemoteMethodCompleted += new EventHandler<MyService.MyRemoteMethodCompletedEventArgs>(serviceClient_MyRemoteMethodCompleted);

            serviceClient.MyRemoteMethodAsync();//調用遠端方法

        }

  步驟3:修改App.xaml.cs,添加Application.Startup事件處理方法Application_Startup。

        private void Application_Startup(object sender, StartupEventArgs e)

            this.RootVisual = new MainPage();

            string serviceAddress = e.InitParams["serviceAddress"].ToString();

            (this.RootVisual as MainPage).InitializeServices(serviceAddress);

  OK,至此,我們已經實作了在程式啟動時調用一個MyRemoteMethod方法。以上代碼稍加改動,我們就可以在程式的任意位置以這種方式調用遠端方法了。

  此方法對WCF Service的調用也有效,手段類似,實作略有不同。