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