设计了一个针对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;
}
}
}