为webHttpBinding JSON Web服务创建异步代理类

时间:2011-08-26 14:04:18

标签: c# silverlight web-services windows-phone-7 asynchronous

我无法在Silverlight中使用webhttpbinding,所以我无法为我的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);
    }
}

1 个答案:

答案 0 :(得分:2)

我现在正在使用RestSharp和我的WP7应用,效果很好。这也意味着我自己并没有处理所有的管道。

作为一个例子,我使用的是一个简单的包装类(url是一个静态字符串属性):

    public static void CallMethod<T>(string endPoint, Method method, Dictionary<string, object> parameters, Action<RestResponse<T>> callback) where T : new()
    {
        if (string.IsNullOrWhiteSpace(url))
            url = Settings.GetSetting("url");
        var client = new RestClient(url);
        var request = new RestRequest(endPoint, method);
        if (parameters == null) parameters = new Dictionary<string, object>();
        foreach (var parameter in parameters)
        {
            request.AddParameter(parameter.Key, parameter.Value);
        }
        client.ExecuteAsync(request, callback);
    }

和示例电话:

    private void MakeACall(int someValue)
    {
        var parameters = new Dictionary<string, object> { { "paramOne", someValue }, { "paramTwo", SomeLocalMethod()} };
        RestAPI.CallMethod<GroupDto>("/Service/Operation", Method.POST, parameters, CallbackMethod);
    }

    private void CallbackMethod(RestResponse<GroupDto> response)
    {
        if (response.StatusCode != HttpStatusCode.OK)
            return;
        ...