Push-Style 資料流範例
Windows Communication Foundation (WCF) 會提供不同模型來處理資料流資料。WCF 會實作 "pull" 模型,其中應用程式程式碼 (服務) 會傳回 Stream 的執行個體,並且依賴較低層級的基礎結構來提取這個資料流的資料,然後將該資料寫出至網路。ASP.NET 則使用 "push" 模型:基礎結構會建立輸出資料流,並使用 OutputStream 屬性,將此資料流提供給應用程式程式碼 (IHttpHandler
)。應用程式程式碼是負責將資料寫入資料流。兩個模型都是有效的方法,並且經常會透過某些方式進行銜接。
注意: |
---|
要建置和執行這個範例,必須安裝 .NET Framework version 3.5。要開啟專案和方案檔,必須要有 Visual Studio 2008。 |
這個範例會示範如何使用 Web 程式設計模型處理使用 ASP.NET 案例的資料流。
服務
服務會實作兩種作業來示範常見的 ASP.NET 案例,如下列程式碼所示。
[OperationContract]
[WebGet(UriTemplate = "images")]
public Message GetDynamicImage()
{
string text = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["text"];
Bitmap theBitmap = GenerateImage(text);
Message response = StreamMessageHelper.CreateMessage(MessageVersion.None, "", "image/jpeg",
delegate(Stream outputStream)
{
theBitmap.Save(outputStream, ImageFormat.Jpeg);
});
return response;
}
請注意 GetDynamicImage()
方法會傳回 Message,而不是傳回 Stream。BodyWriter (DelegateBodyWriter
) 的自訂實作會用來實作 "push" 資料流語意。
DelegateBodyWriter
會接受委派參數,此參數會以輸出資料流做為輸入。
public delegate void StreamWriterDelegate(Stream output);
class DelegateBodyWriter : BodyWriter
{
StreamWriterDelegate writer;
public DelegateBodyWriter(StreamWriterDelegate writer)
: base(false)
{
this.writer = writer;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
writer.WriteStartElement("Binary");
XmlWriterStream stream = new XmlWriterStream(writer);
this.writer(stream);
stream.Close();
writer.WriteEndElement();
}
}
接著在 RawStreamResponseMessage.OnWriteBodyContents()
執行期間叫用 StreamWriterDelegate
委派。
XmlWriterStream
類別是一項配接器,此配接器會在 Message 類別所使用的 XmlDictionaryWriter 上提供 Stream API。
您可以在 Web 瀏覽器中檢視範例的輸出。若要與範例互動,請在服務執行時巡覽至下列 URL。
https://localhost:8000/images?text=Hello, world!
https://localhost:8000/text?text=Hello, world!
若要設定、建置及執行範例
若要建置方案的 C# 或 Visual Basic .NET 版本,請遵循建置 Windows Communication Foundation 範例中的指示。
若要在單一或跨電腦的組態中執行本範例,請遵循執行 Windows Communication Foundation 範例中的指示。
請參閱
工作
Send comments about this topic to Microsoft.
© 2007 Microsoft Corporation. All rights reserved.