Xamarin中的RestSharp认证
问题描述:
我在Xamarin论坛上发现了一个关于同一问题的线程,但该家伙没有得到任何回应,所以我猜这是一个与Xamarin(Android)相关的罕见问题。Xamarin中的RestSharp认证
如果我使用有效凭证,下面的代码片段工作得很好,但如果我使用错误的凭证,或者如果有任何其他原因导致应用程序无法进行身份验证,则会引发WebException(400凭证错误,500在服务器错误等)。
的问题是,我不知道如何处理的异常,它抛出异常,当它进入post()方法...
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);
}
}
答
您使用try..catch块捕捉异常,然后添加任何错误处理逻辑是适当的。
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);
}
答
4xx和5xx范围内的服务器响应会引发WebException。您需要捕获它,从WebException获取状态代码并管理响应。
try{
response = (HttpWebResponse)authClient.Post<AccessTokenResponse>(authRequest);
wRespStatusCode = response.StatusCode;
}
catch (WebException we)
{
wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
// ...
}
如果您需要HttpStatusCode的数值只需使用:
int numericStatusCode = (int)wRespStatusCode ;