简体   繁体   中英

RestSharp authentication in Xamarin

I've found one thread on the Xamarin forums about the same issue, but the guy didn't get any responses, so I'm guessing this is a rare issue related to Xamarin (Android).

The code snippet below works perfectly fine if I use valid credentials, but if I use wrong credentials, or if there is any other reason why the app can't authenticate, a WebException is thrown (400 at wrong credentials, 500 at server error etc.).

The problem is that I don't know how to handle the exception, it throws the exception when it goes into the Post() method...

private void Authenticate()
{
    if (Credentials != null && client.Authenticator == null)
    {
        RestClient authClient = new RestClient(client.BaseUrl);
        RestRequest authRequest = new RestRequest("/token", Method.POST);

            UserCredentials userCred = Credentials as UserCredentials;
            if (userCred != null)
            {
                authRequest.AddParameter("grant_type", "password");
                authRequest.AddParameter("username", userCred.UserName);
                authRequest.AddParameter("password", userCred.Password);
            }

            var response = authClient.Post<AccessTokenResponse>(authRequest);
            response.EnsureSuccessStatusCode();

            client.Authenticator = new TokenAuthenticator(response.Data.AccessToken);
        }
}

Server responses in the range of 4xx and 5xx throw a WebException. You need to catch it, get the status code from WebException and manage the response.

try{
    response = (HttpWebResponse)authClient.Post<AccessTokenResponse>(authRequest);
    wRespStatusCode = response.StatusCode;
}
catch (WebException we)
{
    wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
    // ...
}

If you need the numeric value of the HttpStatusCode just use:

int numericStatusCode = (int)wRespStatusCode ; 

You use a try..catch block to catch the Exception, then add whatever error handling logic is appropriate.

try {
  var response = authClient.Post<AccessTokenResponse>(authRequest);
  response.EnsureSuccessStatusCode();
} catch (WebException ex) {
  // something bad happened, add whatever logic is appropriate to notify the 
  // user, log the error, etc...
  Console.Log(ex.Message);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM