.NET Framework 3.5 的 WCF 建構於 3.0 的擴充點之上,提供一流的 Web 風格服務支援:簡潔的 HTTP 程式模型、JSON 訊息、Syndication (RSS/ATOM) 整合。這使 WCF 成為連接 Web 客戶端 (AJAX、Silverlight、瀏覽器) 的首選平台。
| 類型/屬性 | 命名空間/組件 | 用途 |
|---|---|---|
| WebHttpBinding | System.ServiceModel.Web | HTTP 繫結,支援 REST |
| WebHttpBehavior | System.ServiceModel.Web | 端點行為,啟用 Web 程式模型 |
| WebGetAttribute | System.ServiceModel.Web | 對應 HTTP GET |
| WebInvokeAttribute | System.ServiceModel.Web | 對應非 GET 動作 (POST/PUT/DELETE 等) |
| WebServiceHost | System.ServiceModel.Web | 自動配置 WebHttpBinding + WebHttpBehavior |
| WebServiceHostFactory | System.ServiceModel.Web | IIS 裝載專用,免設定檔 |
[ServiceContract]
public interface IPictureService
{
[OperationContract]
[WebGet(UriTemplate = "picture/{pictureId}")]
Stream GetPicture(string pictureId);
[OperationContract]
[WebGet(UriTemplate = "picture/t/{pictureId}")]
Stream GetPictureThumbnail(string pictureId);
[OperationContract]
[WebInvoke(UriTemplate = "update", Method = "POST")]
void UpdatePictureInfo(PictureInfo info);
}
UriTemplate:REST 風格 URL 範本,大括號內為參數WebGet:唯讀操作,可被快取WebInvoke:狀態變更操作,指定 MethodStream 可直接輸出圖片、檔案等二進位內容<%@ ServiceHost
Language="C#"
Service="PictureService"
Factory="System.ServiceModel.Web.WebServiceHostFactory" %>
web.config 完全不需要 WCF 相關設定。Factory 會自動:
命名空間:System.ServiceModel.Syndication (位於 System.ServiceModel.Web.dll),不依賴 WCF 執行階段,可在任何 AppDomain 使用 (ASP.NET、WPF、Windows Service 等)。
// 讀取 ATOM 來源,轉換為 RSS 2.0 輸出
Uri feedUri = new Uri("https://blogs.msdn.com/justinjsmith/atom.xml");
SyndicationFeed feed = SyndicationFeed.Load(feedUri);
Rss20FeedFormatter formatter = new Rss20FeedFormatter(feed);
XmlWriter writer = XmlWriter.Create(Console.Out, null);
formatter.WriteTo(writer);
writer.Flush();
var feed = new SyndicationFeed("標題", "描述", new Uri("https://example.com"));
feed.Items = new[]
{
new SyndicationItem("項目 1", "內容 1", new Uri("https://example.com/1")),
new SyndicationItem("項目 2", "內容 2", new Uri("https://example.com/2"))
};
// 輸出 ATOM 1.0
var atomFormatter = new Atom10FeedFormatter(feed);
// 輸出 RSS 2.0
var rssFormatter = new Rss20FeedFormatter(feed);
同一服務可同時暴露:
只需在設定檔或程式碼中為同一服務型別加入兩種端點設定。
WCF 3.5 的 HTTP 程式模型增強,填補了 SOA 方案中「服務與 Web 客戶端通訊」的關鍵缺口。WebHttpBinding、WebGet/WebInvoke、WebServiceHostFactory 三劍客讓 REST 服務開發極度簡潔;Syndication 命名空間讓 RSS/ATOM 內容建立與消費不再繁瑣。這是微軟 SOA 戰略邁向開放 Web 的重要一步。