新建Rest服務接口:
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
}接著新建一個服務實現類:
public class Service1 : IService1
{
public string GetData(int value)
{
int i = 0;
int j = 5 / i;
return string.Format("You entered: {0}", value);
}
}
在這裡讓Service1 拋出”divided by zero exception:”
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="WcfService1.Service1">
</service>
</services>
</system.serviceModel>
在這裡注意<serviceDebug includeExceptionDetailInFaults="true" />
在Silverlight 客戶端添加服務引用,名稱為:ServiceReference1.
在頁面上添加一個按鈕,按鈕的Click事件代碼如下:
private void Button_Click(object sender, RoutedEventArgs e)
{
Service1Client client = new ServiceReference1.Service1Client();
client.GetDataCompleted += new EventHandler<GetDataCompletedEventArgs>(client_GetDataCompleted);
client.GetDataAsync(35); //Try GetData
}
void client_GetDataCompleted(object sender, ServiceReference1.GetDataCompletedEventArgs e)
{
}
運行,結果如下:
可以看到實際的異常是“嘗試除以0”,但是由於浏覽器限制,所有的異常都是NotFound。
在msdn上有兩種方法可以解決這個問題,
最簡單的就是在App.xaml.cs代碼裡面使用RegisterPrefix來使用備用客戶端 HTTP 堆棧
public App()
{
bool bRegisterPrefix = WebRequest.RegisterPrefix(http://localhost:9541/, WebRequestCreator.ClientHttp);
//other Code
}
再次運行代碼:
這是SL調用WCF服務如何處理異常的方式,那麼調用Rest服務呢?
首先要修改Web.config 節點下的serviceModel以讓它支持Rest。
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="EndpointBehavior">
<webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"
faultExceptionEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="WcfService1.Service1">
<endpoint behaviorConfiguration="EndpointBehavior" binding="webHttpBinding"
bindingConfiguration="" name="Rest" contract="WcfService1.IService1" />
</service>
</services>
</system.serviceModel>
在這裡要設置webHttp 節點的faultExceptionEnabled=true.並且設置serviceDebug 的includeExceptionDetailInFaults 為true。
OK,服務的Web.config文件已經配置完畢了,接下來要為GetData方法添加WebGet特性修飾了。
public class Service1 : IService1
{
[WebGet()]
public string GetData(int value)
{
int i = 0;
int j = 5 / i;
return string.Format("You entered: {0}", value);
}
}
運行:
可以看到得到了異常信息了。
注意:別忘記了添加跨域和授權文件:crossdomain.xml 和 clientaccesspolicy.xml 到網站根目錄。
同樣,修改SL客戶端頁面,添加一個Button,button的代碼事件為:
private void btnRest_Click(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
}
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
&n