在Xamarin.forms

时间:2015-05-01 20:20:58

标签: asp.net-web-api login xamarin xamarin.forms

用户提交登录信息后,按下登录按钮,将调用以下方法;

public Page OnLogInButtonClicked (string email, string password)
{
    var client = new RestClient("http://babyAPI.com");
    var request = 
        new RestRequest("api/ApiKey?email=" + email + "&password=" + password, Method.GET);

    var queryResult = client.Execute(request);

    if (queryResult.StatusCode == HttpStatusCode.OK)
    {
        var deserial = new JsonDeserializer();
        var x = deserial.Deserialize<ApiKey>(queryResult);

        return;
    }
    else
    {
        return;
    }

}

这是正确的方法吗?如果用户通过身份验证,我需要导航到新页面,否则显示身份验证失败。怎么办?

1 个答案:

答案 0 :(得分:0)

你的问题很广泛。你想解决什么?

以下是我认为可以在此代码中改进的内容。假设这是一个ViewModel类 - 如果它没有在MVVM中的Xamarin上读取。我建议你也阅读Separation of Concerns(另见关于DRY和单一责任的底层链接)

// make the method async so your UI doesn't lock up
public async Task AuthenticateAndNavigate(string email, string pass){
  // your MVVM framework may have IsBusy property, otherwise - define it
  // it should be bindable so you can use it to bind activity indicators' IsVisible and buttons' IsEnabled 
  IsBusy = true; 
  try{
    // split out the code that talks to the server in a separate class - don't mix UI, ViewModel and server interactivity (separation of concerns principle)
    // the assumption here is that a null is returned if auth fails
    var apiKey = BabyApi.GetApiKey(email, pass);

    // the Navigation property below exists in some MVVM frameworks, otherwise it comes from a Page instance that calls this code
    if (apiKey!=null) 
      await Navigation.PushModalAsync(new HomePage());
    else 
      await Navigation.PushAsync(new FailedToAuthenticatePage()); // or just do nothing
  } catch { 
    await Navigation.PushAsync(new FailedToAuthenticatePage { Error: x.Message });
  } finally {
    IsBusy = false;
  }
}