把 JSON 當作前後台之間的數據協議,聽起來簡單,真正落到工程裡卻有不少細節:後台用什麼方式輸出、客戶端怎麼解析、異常如何表達。以下按這三條線梳理。
用 WCF 提供 JSON 需要注意三處配置。
A. 契約定義:在 WebInvokeAttribute 或 WebGetAttribute 中把 ResponseFormat 設為 WebMessageFormat.Json:
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "IsExistSSID/{SSID}",
RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
B. EndPointBehavior 使用 webHttp:
<behavior name="UIAjaxEndpointBehavior"> <webHttp /> <PolicyEndPointBehavior /> </behavior>
C. Binding 使用 webHttpBinding:
<service name="XX.DeviceUIService" behaviorConfiguration="UIAjaxServiceBehavior"> <endpoint address="" behaviorConfiguration="UIAjaxEndpointBehavior" binding="webHttpBinding" contract="DeviceUIServiceContract" /> </service>
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory()) 已加入,MVC 3 默認已經做了這件事;JsonResult;return Json(XXX) 輸出,XXX 必須是可序列化類型。這兩種方式也能實現,但屬於較早期的做法。WCF 已被微軟定位為其通信平台,因此非 MVC 環境優先選 WCF,把數據接口視為系統對外服務;而在 .NET MVC 環境下直接用 JsonResult 更省事。
用 jQuery Ajax 時,把 dataType 設為 'json',框架會自動把響應轉成對象:
$.ajax({
url: 'urladdress',
type: 'GET',
contentType: 'application/json',
dataType: 'json',
cache: false,
async: false,
error: JQueryAjaxErrorHandler,
success: function (result) { }
});
HTTP 協議本身已經定義了狀態碼語義:200 表示服務端正常返回,404 表示資源不存在,401 未授權,417 表示未滿足服務端期望,301 是重定向。Web 應用理應遵循這套約定,而不是把所有結果都包成 200。
在 WCF 環境下要分兩步。第一步,給每個方法加上 FaultContract:
FaultContract(typeof(WebFaultException<WebErrorDetail>))
第二步,捕獲異常並轉為帶狀態碼的 Fault:
try
{
//BussinessCode.....
}
catch (DuplicateException ex)
{
throw new WebFaultJsonFormatException<WebErrorDetail>(
new WebErrorDetail(ex.Message, ex), HttpStatusCode.ExpectationFailed);
}
catch (NotExistException ex)
{
throw new WebFaultJsonFormatException<WebErrorDetail>(
new WebErrorDetail(ex.Message, ex), HttpStatusCode.ExpectationFailed);
}
catch (AppException ex)
{
throw new WebFaultJsonFormatException<WebErrorDetail>(
new WebErrorDetail(ex.Message, ex), HttpStatusCode.ExpectationFailed);
}
catch (Exception ex)
{
throw new WebFaultJsonFormatException<WebErrorDetail>(
new WebErrorDetail(ex.Message, ex), HttpStatusCode.ExpectationFailed);
}
其中 WebFaultJsonFormatException 的定義如下:
[Serializable, DataContract]
public class WebFaultJsonFormatException<T> : WebFaultException<T>
{
public WebFaultJsonFormatException(T detail, HttpStatusCode statusCode)
: base(detail, statusCode)
{
ErrorDetailTypeValidator(detail);
}
public WebFaultJsonFormatException(T detail, HttpStatusCode statusCode, IEnumerable<Type> knownTypes)
: base(detail, statusCode, knownTypes)
{
ErrorDetailTypeValidator(detail);
}
private void ErrorDetailTypeValidator(T detail)
{
foreach (DataContractAttribute item in detail.GetType().GetCustomAttributes(typeof(DataContractAttribute), true))
{
if (item.IsReference)
throw new WebFaultJsonFormatException<PureWebErrorDetail>(
new PureWebErrorDetail("The DataContractAttribute property 'IsReference' which applied on {0} can't be true when the transfer code type is JSON fromat.", typeof(T).FullName),
HttpStatusCode.ExpectationFailed);
}
}
}
[Serializable, DataContract(IsReference = false)]
public class PureWebErrorDetail
{
public PureWebErrorDetail(string message, params object[] args)
{
this.Message = string.Format(message, args);
}
[DataMemberAttribute]
public string Message { get; set; }
}
這段代碼解決的是一個很實際的坑:JSON 不支援循環引用,而 XML 支援。所以 JSON 序列化時 DataContract 的 IsReference 不能為 true。WebFaultJsonFormatException 的作用就是提前檢查這一點,若為 true 則拋出人類可讀的錯誤。如果不用這層包裝,jQuery Ajax 收到的會是一個 15 開頭的異常狀態碼,它並不落在正常 HTTP 狀態碼範圍內,前端根本無法分類處理。
早期很容易設計出這樣的通用返回結構:
[DataContract]
public class TmResult
{
[DataMember]
public bool Success { get; set; }
[DataMember]
public string ErrorMessage { get; set; }
[DataMember]
public string FullMessage { get; set; }
[DataMember]
public string CallStack { get; set; }
}
[DataContract]
public class TmResult<T> : TmResult
where T : class
{
[DataMember]
public T Model { get; set; }
}
每個接口都返回 Success 標誌和 ErrorMessage,效果是所有響應的 HTTP 狀態碼永遠是 200。看著整齊,實際上把協議本身的表達能力浪費掉了:前端要寫一堆 if 判斷,監控系統無法按狀態碼報警,緩存和重試策略也無從下手。
想通這一層之後就會發現,既然走的是 Web,不如讓程序更符合 HTTP 的定義——該 404 就 404,該 401 就 401,該 500 就 500。標準化的價值就在這裡:熟悉協議、熟悉編程模型和 API,開發反而更簡單。
以上是按個人理解整理,有不到位之處歡迎指正。