1:新建Silverlight4应用程序,名称为SLClient,选择web承载。
2:在MainPage下新建4个按钮,代码如下:
< Grid x:Name ="LayoutRoot" Background ="White" > < StackPanel > < Button Content ="GET" x:Name ="Get" Click ="Get_Click" /> < Button Content ="PUT" x:Name ="Put" Click ="Put_Click" /> < Button Content ="POST" x:Name ="Post" Click ="Post_Click" /> < Button Content ="DELETE" x:Name ="Delete" Click ="Delete_Click" /> </ StackPanel > </ Grid > 3:在上一篇的随便中,服务的地址都是 ,我门首先调用Get服务。
private void Get_Click( object sender, RoutedEventArgs e) { WebClient webClient = new WebClient(); webClient.DownloadStringCompleted += (o, ea) => { MessageBox.Show(ea.Result); }; webClient.DownloadStringAsync( new Uri( " http://localhost:19598/ProductService.svc/Product " )); } 在这里,构造WebClient对象用来提交请求,基本的代码就不解释了。
我们点击Get按钮,弹出错误提示如下图:
这里的主要原因是Silverlight跨域需要证书和授权。
5:在上一篇文章的Web跟目录下新建clientaccesspolicy.xml和crossdomain.xml。
代码结构如下图:
clientaccesspolicy.xml:
View Code crossdomain.xml:
View Code 6:我们继续调用Get服务,终于调用成功,结果如下图:
7:调用POST服务,代码如下:
private void Post_Click( object sender, RoutedEventArgs e) { WebClient webClient = new WebClient(); string data = " {\"Id\":\"5cee6c7c-9976-424b-99ab-e9cc90585105\",\"Name\":\"111\"} " ; webClient.UploadStringCompleted += (o, ea) => { MessageBox.Show(ea.Result); }; webClient.UploadStringAsync( new Uri( " http://localhost:19598/ProductService.svc/Product " ), " POST " ,data); } 点击POST按钮,弹出
这个问题主要是因为服务器并不知道data是什么东西,为了让服务器明白data是json数据,我们需要设置
Content-Type:application/json;
改好后的代码如下:
private void Post_Click( object sender, RoutedEventArgs e) { WebClient webClient = new WebClient(); // 设置请求的内容格式为application/json。 webClient.Headers[HttpRequestHeader.ContentType] = " application/json " ; // 构造json数据。 string data = " {\"Id\":\"5cee6c7c-9976-424b-99ab-e9cc90585105\",\"Name\":\"111\"} " ; webClient.UploadStringCompleted += (o, ea) => { MessageBox.Show(ea.Result); }; webClient.UploadStringAsync( new Uri( " http://localhost:19598/ProductService.svc/Product " ), " POST " ,data); } 8:尝试调用PUT,DELETE,代码如下:
private void Put_Click( object sender, RoutedEventArgs e) { WebClient webClient = new WebClient(); // 设置请求的内容格式为application/json。 webClient.Headers[HttpRequestHeader.ContentType] = " application/json " ; // 构造json数据。 string data = " {\"Id\":\"5cee6c7c-9976-424b-99ab-e9cc90585105\",\"Name\":\"111\"} " ; webClient.UploadStringCompleted += (o, ea) => { MessageBox.Show(ea.Result); }; webClient.UploadStringAsync( new Uri( " http://localhost:19598/ProductService.svc/Product " ), " PUT " , data); } 点击PUT按钮,结果弹出提示:
在监视窗口输入$exception可以查看当前的异常。
可以很明显的得知此请求不支持指定的方法,也就是说WebClient不支持PUT,DELETE,那我们又该如何做呢,下回分解..
本文转自LoveJenny博客园博客,原文链接:http://www.cnblogs.com/LoveJenny/archive/2011/04/29/silverlight_Rest_WCF.html,如需转载请自行联系原作者