首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

實戰 Web Service 開發精要:序列化限制、實體設計與 Silverlight 協同架構

     編輯:關於ASP.NET

Web Service (ASMX/WCF) 仍是企業級系統集成主力。本文總結實體類設計禁忌、序列化陷阱、以及 Silverlight 客戶端協同的分層架構實踐。

架構分層

專案結構圖

  • Jasen.SilverlightService:Silverlight 客戶端專案
  • Jasen.SilverlightService.Core:共享契約/實體/演算法庫(職責鏈模式實現路徑演算法)
  • Jasen.SilverlightService.Web:Web Service 發布站點

實體類設計鐵律

規則錯誤示範正確示範原因
不可使用介面作為返回類型IList<T>List<T> 或 T[]序列化器需具體型別實例化
型別必須可序列化未標記 [Serializable] 或 [DataContract]標記 [DataContract]、成員 [DataMember]WCF DataContractSerializer 強制要求
必須有無參構造函式public Entity(int id) { ... }public Entity() { } + public Entity(int id) : this() { }反序列化時先 new() 再設屬性
唯讀屬性不序列化public string Name { get; }public string Name { get; set; }無 setter 無法反序列化賦值

實體類範例:ServerInfo

[DataContract]
public class ServerInfo {
    [DataMember] public string Title { get; set; }
    [DataMember] public string Content { get; set; }
    [DataMember] public bool IsPublished { get; set; }

    // 唯讀欄位:僅序列化輸出,不接受客戶端輸入
    [DataMember] public string SmallTitle { get; } = "small title";
    [DataMember] public bool IsSucceed { get; } = true;
}

服務合約與實現

[ServiceContract]
public interface IDataService {
    [OperationContract]
    ServerInfo GetData(string param); // 參數、返回皆為具體型別
}

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DataService : IDataService {
    public ServerInfo GetData(string param) {
        // 調用 Core 庫職責鏈演算法
        var result = AlgorithmChain.Execute(param);
        return new ServerInfo { Title = result.Title, Content = result.Detail };
    }
}

Silverlight 客戶端調用

var client = new DataServiceClient();
client.GetDataCompleted += (s, e) => {
    if (e.Error == null) {
        var info = e.Result;
        // 繫結 UI:info.Title, info.Content
    }
};
client.GetDataAsync("paramValue");

常見坑位與對策

  • 循環引用:實體雙向導航屬性 → 設 [DataContract(IsReference=true)] 或 DTO 扁平化。
  • 大數據傳輸:啟用 MTOM 編碼 <binding messageEncoding="Mtom">,分塊傳輸。
  • 異常屏蔽:WCF 預設不傳輸堆疊追蹤 → 實作 IErrorHandler 返回友善 FaultException。
  • 跨域調用:Silverlight 需 clientaccesspolicy.xml 或 crossdomain.xml 部署於網站根目錄。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved