我尝试实现登录我的应用程序。而且我需要在页面开始加载之前登录,因为当一切正常时,我会转到第二页,如果不是第一页。为此,我像这样设置 WMAppManifest:
<DefaultTask Name="_default" NavigationPage="" />
当我执行我的异步方法时,并行应用程序开始加载页面,但它是空的,所以我的应用程序冻结了。
我的 Application_Launching 看起来如何:
private async void Application_Launching(object sender, LaunchingEventArgs e)
{
bool logged = await LogIn("login", "pass");
Uri nUri = null;
if (logged)
{
nUri = new Uri("/SecondPage.xaml", UriKind.Relative);
}
else
{
nUri = new Uri("/FirstPage.xaml", UriKind.Relative);
}
((App)Application.Current).RootFrame.Navigate(nUri);
}
异步方法登录:
private async Task<bool> LogIn(string login, string password)
{
string str_login_number = login;
string str_login_pass = password;
JObject jo = new JObject();
jo.Add("number", str_login_number);
jo.Add("pass", str_login_pass);
JsonWorker jWorker = new JsonWorker();
var response = await jWorker.sendJSON("url", jo);
string str_responseformjson = await jWorker.getJSON(response);
jo = JObject.Parse(str_responseformjson);
if (jo["response"].ToString().Equals("ok"))
{
return true;
}
else
{
return false;
}
}
这是我的班级 JsonWorker 的代码:
class JsonWorker
{
public async Task<HttpWebResponse> sendJSON(string requestUrl, JObject jsonObjesct)
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(requestUrl);
request.ContentType = "text/plain; charset=utf-8";
request.Method = "POST";
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(jsonObjesct.ToString());
Stream x = await request.GetRequestStreamAsync();
await x.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
x.Close();
HttpWebResponse response = (HttpWebResponse)(await request.GetResponseAsync());
return response;
}
public async Task<string> getJSON(
HttpWebResponse response)
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
string str_responsefromjson = await sr.ReadToEndAsync();
sr.Close();
stream.Close();
return str_responsefromjson;
}
}
请帮忙。