Я не могу использовать webhttpbinding в Silverlight, поэтому я не могу добавить ссылку на службу к моей REST wcf-службе и заставить Visual Studio сгенерировать прокси-класс, поэтому мне нужно создать свой собственный. создать мой собственный асинхронный прокси-класс REST для использования в Silverlight, используя что-то вроде WebClient?
Ниже приведен код, реализующий прокси-класс, который я создал, и правильно ли я его кодирую?
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);
}
}