silverlight与webapi 通讯的辅助对象

设计了一个针对silverlight 与 webapi 通讯的一个辅助对象,以下是源代码。

using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace HMG.SilverlightApp.Common
{
    public class HttpComunication<T>
    {
        private WebClient _client;
        private Action<T> _successCallback = null;
        private Action<string> _errorCallback = null;
        public HttpComunication()
        {
            _client = new WebClient();

            _client.DownloadStringCompleted += DownloadStringAsyncCompleted;

        }

        public void Get(string controller, Action<T> successCallback, Action<string> errorCallback, params object[] parameter)
        {
            this._successCallback = successCallback;
            this._errorCallback = errorCallback;

            var uriStr = GetUri(controller, parameter);

            _client.DownloadStringAsync(uriStr);
        }
<span style="white-space:pre">	</span>
        public void Post<M>(string controller, Action<T> successCallback, Action<string> errorCallback, M postData, params object[] parameter)
        {
            this._successCallback = successCallback;
            this._errorCallback = errorCallback;

            var uriStr = GetUri(controller, parameter);

            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(M));
            string postString = "";
            using (MemoryStream stream = new MemoryStream())
            {
                jsonSerializer.WriteObject(stream, postData);
                byte[] json = stream.ToArray();
                postString = Encoding.UTF8.GetString(json, 0, json.Length);
            }

            _client.UploadStringAsync(uriStr, "Post", postString);
        }

        private Uri GetUri(string controller, object[] parameter)
        {
            string url = string.Format("http://localhost:1360/api/{0}", controller);
            foreach (var item in parameter)
            {
                if (item != null)
                    url += "/" + item;
            }

            return new Uri(url);
        }

        private void DownloadStringAsyncCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
                var buffer = Encoding.UTF8.GetBytes(e.Result);
                T jsonResult;
                using (Stream stream = new MemoryStream(buffer))
                {
                    jsonResult = (T)jsonSerializer.ReadObject(stream);
                }
                if (this._successCallback != null)
                {
                    this._successCallback(jsonResult);
                    this._successCallback = null;
                }
            }
            catch (Exception ex)
            {
                this._errorCallback(ex.Message);
                this._errorCallback = null;
            }
        }
    }

}

调用的示例代码如下,这些代码写在了对应页面的viewmodel中。

 private ICommand loginBtnClick;  
public ICommand LoginBtnClick
        {
            get
            {
                if (loginBtnClick == null)
                    loginBtnClick = new DelegateCommand(() =>
                    {
                        HttpComunication<LoginResultModel> cuMg = new HttpComunication<LoginResultModel>();
                        cuMg.Get("Login", x =>
                        {
                            if (x.IsSuccess)
                            {
                                //goto new page
                                MessageText = "登录成功!";
                                ((App)Application.Current).RedirectTo(new MainPage());
                            }
                            else
                            {
                                MessageText = x.Error;
                            }

                        },
                        x =>
                        {
                            //excaption message
                            MessageText = x;
                        },
                        userNameText, passwordText);
                    });

                return loginBtnClick;
            }
        }
以下是webapi中controll 中的代码:

using HMG.Web.DomianModel;
using HMG.Web.Models.API;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace HMG.Web.Controllers.API
{
    [RoutePrefix("api/Login")]
    public class LoginController : ApiController
    {
        [Route("{userName}/{pwd}")]
        public LoginResultModel Get(string userName, string pwd)
        {
            LoginResultModel r = new LoginResultModel();
            try
            {

                if (AccountManager.Current.GetByUserName(userName).Password != pwd)
                {
                    r.Error = "错误的密码!";
                }
            }
            catch (DomainException ex)
            {
                r.Error = ex.Message;
            }

            return r;
        }

    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值