gpt4 book ai didi

c# - Xamarin 中的 RestSharp 身份验证

转载 作者:行者123 更新时间:2023-11-29 20:21:23 25 4
gpt4 key购买 nike

我在 Xamarin 论坛上发现了一个关于同一问题的帖子,但是那个人没有得到任何回复,所以我猜这是一个与 Xamarin (Android) 相关的罕见问题。

如果我使用有效的凭据,下面的代码 fragment 工作得很好,但如果我使用错误的凭据,或者如果有任何其他原因导致应用程序无法进行身份验证,则会抛出 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);
}
}

最佳答案

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 ; 

关于c# - Xamarin 中的 RestSharp 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33122673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com