1. change interface, add WebGet
[OperationContract] [WebGet(UriTemplate = "l/{lower}/u/{upper}", ResponseFormat = WebMessageFormat.Json)] int SecretNumber(string lower, string upper);
[OperationContract] [WebGet(UriTemplate = "sn?l={lower}&u={upper}", ResponseFormat = WebMessageFormat.Json)] int SecretNumber(int lower, int upper);
2. add to svc markup
<%@ ServiceHost Language="C#" Debug="true" Service="Restful_service.Service1" CodeBehind="Service1.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
3. 为了能让silverlight程序调用restful service 必须添加crossdomain.xml在service project的根目录
<cross-domain-policy> <allow-http-request-headers-from domain="*" headers="*"/> </cross-domain-policy>
4. use restful service
(1) Sync
private string getResponse(Uri uri) { WebClient client = new WebClient(); byte[] response = client.DownloadData(uri); String respnStr = System.Text.Encoding.Default.GetString(response); return respnStr; }
(2) Async
Uri uri = new Uri(full); client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client1_DownloadStringCompleted); client.DownloadStringAsync(uri);
void client1_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error != null) { string data = e.Error.ToString(); label1.Content = "--------has error:" + data + "************"; label1.Content = data; return; } secNum = e.Result; }