學Silverlight 2系列(33):Silverlight 2應用Web Service兩例

來源:互聯網
上載者:User

概述

我們知道,在Silverlight 2中提供了豐富的網路通訊API,包括支援SOAP服 務、REST服務、基於HTTP通訊、Socket通訊等。本文我將通過幾個樣本來示範如 何在Silverlight 2中應用Web Service實現檔案上傳和電子郵件發送。

使用Web Service上傳檔案

我將通過一個樣本來展示如何使用Web Service向伺服器上傳檔案,首先建立 Silverlight項目,並在Web測試專案中添加一個ASP.NET Web Service檔案。現 在來實現相關的WebMethod,在此方法中,將會接收兩個參數:位元組數組和檔案 副檔名,並會在伺服器上建立檔案,如下代碼所示:

public class FileService : WebService
{
   [WebMethod]
  public int UploadFile(byte[] FileByte, String FileExtention)
  {
     FileStream stream = new FileStream(String.Format(@"D:\example.{0}", FileExtention),FileMode.CreateNew);
    stream.Write(FileByte, 0, FileByte.Length);
     stream.Close();
    return FileByte.Length;
  }
}

添加一個簡單的介面,供使用者選擇本地檔案,我們將在按鈕單擊單擊事件中 調用Web Service,如下代碼所示:

<Canvas Background="#FF333333">
  <TextBox x:Name="txtFile" Height="30" Width="300" Canvas.Top="120"
        Canvas.Left="30" Style="{StaticResource textBoxStyle}"></TextBox>
  <Button x:Name="btnUpload" Width="60" Content="上 傳" Height="30"
        Canvas.Left="340" Canvas.Top="120" Style="{StaticResource buttonStyle}"
       Click="OnUploadClick"></Button>
  <TextBlock x:Name="tblStatus" Canvas.Left="30" Canvas.Top="160"
        FontSize="14" Foreground="White" Text=""></TextBlock>
</Canvas>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.