0
我無法在Silverlight中使用webhttpbinding,因此我無法將服務引用添加到我的REST wcf服務並獲得visual studio生成代理類,因此我必須創建我的自己,我想知道如何創建我自己的異步REST代理類以使用Silverlight使用類似WebClient的東西?爲webHttpBinding創建異步代理類JSON web服務
下面是我創建的一些代碼,它實現了一個代理類,我是否正確地編碼它?
public class RestProxy
{
private const string REST_URL = "http://.../RestService.svc";
private delegate int AddDelegate(int num1, int num2);
private delegate void AddCompleted(int result);
public AddCompleted AddOnCompleted { get; set;}
public int Add(int num1, int num2)
{
const string rest_method = "/Add";
//create json serializer.
JavaScriptSerializer serializer = new JavaScriptSerializer();
//add parameters to send into dictionary.
Dictionary<string, string> numberData = new Dictionary<string, string>();
postData.add("number1", num1.toString());
postData.add("number2", num2.toString());
//serialize dictionary to json.
string jsonData = serializer.Serialize(numberData);
//make request
string responseData = MakeRequest(REST_URL + rest_method, jsonData);
//deserialize json response data to dictionary.
Dictionary<string, string> numberResult = (Dictionary<string,string>)serializer.Deserialize(responseData, typeof(Dictionary<string,string>));
return Convert.toInt32(numberResult["AddResult"]);
}
public void AddAsync(int num1, int num2)
{
AddDelegate addAsync = new AddDelegate(this.Add);
addAsync.BeginInvoke(int num1, int num2, (IAsyncResult async_result) => {
//get caller
AsyncResult result = (AsyncResult)async_result;
AddDelegate caller = (AddDelegate)result.AsyncDelegate;
//get result.
int resultNumber = caller.EndInvoke(result);
//call callback delegates.
if(AddOnCompleted != null) AddOnCompleted(resultNumber);
}, null);
}
protected string MakeRequest(string address, string data_to_send)
{
WebClient webclient = new WebClient();
byte[] responseBytes = webclient.UploadData(new Uri(address), "POST", Encoding.ASCII.GetBytes(data_to_send));
return Encoding.ASCII.GetString(responseBytes);
}
public static void Main(string[] args)
{
RestProxy proxy = new RestProxy();
proxy.AddOnCompleted += new AddOnCompleted((int result) => { Console.WriteLine(result)});
proxy.AddAsync(10, 10);
}
}
感謝理查德,但是我想自己編寫代理類而不使用任何第三方庫。 – rjs