处理HttpClient响应和异常的最佳实践是什么?

时间:2017-08-09 08:11:11

标签: c# xamarin xamarin.forms dotnet-httpclient

我在System.Net.Http.HttpClient项目中使用Xamarin.Forms,我正在尝试处理响应和异常。根据响应或异常,我试图在UI端向用户显示警报/提示。这是我到目前为止所做的。

HttpClient致电

public async Task<LoginResponse> Login(User user)
{
    string PostLoginEndPoint = "/login";
    Uri uri = new Uri(BaseAddress + LoginEndPoint);
    LoginResponse loginResponse = null;

    try
    {
        var userJson = JsonConvert.SerializeObject(user);
        var content = new StringContent(userJson, Encoding.UTF8, "application/json");

        HttpResponseMessage response = null;
        response = await client.PostAsync(uri, content);

        if (response.IsSuccessStatusCode)
        {
            string responseContent = await response.Content.ReadAsStringAsync();

            if (!string.IsNullOrWhiteSpace(responseContent))
            {
                loginResponse = JsonConvert.DeserializeObject<LoginResponse>(responseContent);
            }
        }
    }
    catch(Exception ex)
    {
        loginResponse = JsonConvert.DeserializeObject<LoginResponse>("Failed!");
        Debug.WriteLine("Exception:" + ex.ToString());
    }

    return loginResponse;
}

和UI端

private async void Submit_Clicked(object sender, EventArgs e)
{
    try
    {
        if (!IsValid())
        {
            await DisplayAlert(AlertDialogHelper.loginDialogTitle, AlertDialogHelper.loginValidationFailedMsg, AlertDialogHelper.okButtonText);
            return;
        }

        SpinnerLayout.IsVisible = true;

        User user = new User {
            username = UserNameTxt.Text,
            password = PasswordTxt.Text
        };

        LoginResponse response = await LoginService.Login(user);

        if (response != null)
        {
            if (!string.IsNullOrWhiteSpace(response.token))
            {
                Settings.Token = response.token;
                await DisplayAlert(AlertDialogHelper.loginDialogTitle, AlertDialogHelper.loginSuccessMsg, AlertDialogHelper.okButtonText);
                await Navigation.PushAsync(new LandingPage());
            }
            else
            {
                await DisplayAlert(AlertDialogHelper.loginDialogTitle, AlertDialogHelper.loginFailedMsg, AlertDialogHelper.okButtonText);
            }
        }
        else
        {
            await DisplayAlert(AlertDialogHelper.loginDialogTitle, AlertDialogHelper.errorMsg, AlertDialogHelper.okButtonText);
        }
    }
    catch (Exception ex)
    {
        await DisplayAlert(AlertDialogHelper.loginDialogTitle, AlertDialogHelper.errorMsg, AlertDialogHelper.okButtonText);
        Debug.WriteLine("Exception: " + ex.ToString());
    }
    finally
    {
        SpinnerLayout.IsVisible = false;
    }
}

我想知道的是,如何在UI和HttpClient方面改进我的实现,以实现更有效的响应/错误处理和更清晰的代码。 任何帮助将不胜感激。

0 个答案:

没有答案