Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

await HttpClient.PostAsync() reports System.NullReference but HttpClient.PostAsync().Result doesn't

$
0
0

Hi all,

in my app I need to check if user is logged in. We are using Oath2 and I only want to check if refresh token is valid.
I do this in OnStart method. I have simplified the code a bit but the exception is still thrown in

var response = await httpClient.PostAsync(url, content); 

if I replace it with:

var response = httpClient.PostAsync(url, content).Result; 

then the crash does not happen. What am I missing ?

App.xaml.cs

protected override async void OnStart()
    {
        // Handle when your app starts

        try
        {
            RefreshToken refreshToken = new RefreshToken((Application.Current as App).RefreshToken);

            var haveValidRefreshToken = await IsRefreshTokenValid();
            if (haveValidRefreshToken.IsSuccess)
                MainPage = new NavigationPage(new LoginPage());
            else
                MainPage = new NavigationPage(new Views.MainTabbedPage());
        }
        catch ( UserServiceException )
        {
            MainPage = new NavigationPage(new LoginPage());
        }
    }

    static async Task<RestResponse> IsRefreshTokenValid()
    {
        var content = new StringContent("", Encoding.UTF8, "application/json");
        var httpClient = new HttpClient();
        string url = "13.74.21.155:8080";
        var response = await httpClient.PostAsync(url, content);    // <==== System.NullReference thrown
        return new RestResponse
        {
            IsSuccess = response.IsSuccessStatusCode,
            Status = response.StatusCode,
            Content = await response.Content.ReadAsStringAsync()
        };
    }

Viewing all articles
Browse latest Browse all 77050

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>