0
我們正在嘗試確定發送到我們的服務的請求的類型,以便我們可以以正確的格式返回數據。下面的代碼完美地工作,除了我們希望避免將它放在我們創建的每一個服務的「獲取」方法中。任何人都可以提供關於如何實現任何基類或可擴展點的建議,以便我們不必複製和粘貼此片段到處?用於確定WCF中REST響應類型的建議模式
[WebGet(UriTemplate = "Case/{id}")]
public SampleItem Get(string id)
{
string formatQueryStringValue = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
if (!string.IsNullOrEmpty(formatQueryStringValue))
{
if (formatQueryStringValue.Equals("xml", System.StringComparison.OrdinalIgnoreCase))
{
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
}
else if (formatQueryStringValue.Equals("json", System.StringComparison.OrdinalIgnoreCase))
{
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
}
else
{
throw new WebFaultException<string>(string.Format("Unsupported format '{0}'", formatQueryStringValue), HttpStatusCode.BadRequest);
}
}
return new SampleItem() { StringValue = "test" };
}
如果你是.NET 4,則框架將確定的內容類型的客戶端可以理解併發送這種格式的迴應。 – Rajesh 2012-03-19 16:17:05