在将网址( Constants.UrlLoginUser )更改为子域名之前,以下代码运行正常。我正在使用“基本”身份验证。当我使用原始URL时,它工作正常。我知道重定向发生时正在清除HttpClient Authentication头。有没有办法让它与重定向网址一起使用?我试过使用CredentialCache没有任何成功。我通过重定向网址获得了“ 401 Unauthorized ”回复。
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("email", TxtEmail.Text);
client.DefaultRequestHeaders.Add("password", TxtPassword.Text);
client.DefaultRequestHeaders.Authorization = HttpClientHelper.NdAuth;
var result = await client.GetAsync(Constants.UrlLoginUser);
}
这里提供了一个潜在的解决方案answer,但它有点像黑客。
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
// Authorization header has been set, but the server reports that it is missing.
// It was probably stripped out due to a redirect.
var finalRequestUri = response.RequestMessage.RequestUri; // contains the final location after following the redirect.
if (finalRequestUri != requestUri) // detect that a redirect actually did occur.
{
if (IsHostTrusted(finalRequestUri)) // check that we can trust the host we were redirected to.
{
response = client.GetAsync(finalRequestUri).Result; // Reissue the request. The DefaultRequestHeaders configured on the client will be used, so we don't have to set them again.
}
}
}
在Xamarin Forms上有更清晰的方法来实现这一目标吗?