我有一个.net项目,它与后端java服务器(REST)进行通信,以进行所有相关的业务操作。我正在使用HttpClient发送我的请求。 我的问题在于:如果请求失败,即从.Result引发了AggregateException,并且'任务被取消了'在几乎所有其他对服务器的调用中,我的HttpClient实例丢失了Accept和Accept-Language DefaultRequestHeaders。 我在实例化客户端的方式上尝试了许多不同的变体,无论是作为静态类还是通过webconfig,但它在所有情况下都会发生,我没有任何想法。 请参阅下面的代码。 我从我的web.Config加载属性,这是我的对象,它被正确填写(从here得到):
public sealed class AthenaHttpClients : ConfigurationSection
{
private HttpClient _client { get; set; }
[ConfigurationProperty("athenaFactoryClient", IsRequired = true)]
public AthenaFactoryHttpClient FactoryClient
{
get { return (AthenaFactoryHttpClient)base["athenaFactoryClient"]; }
set { base["athenaFactoryClient"] = value; }
}
private static AthenaHttpClients instance = null;
public static HttpClient GetClient()
{
if (instance == null)
{
instance = (AthenaHttpClients)WebConfigurationManager.GetSection("athenaHttpClients");
}
instance.FactoryClient.Client = HttpClientFactory.Create(new CustomDelegatingHandlerTokenRefresher());
instance.FactoryClient.Client.BaseAddress = new Uri(ConfigurationManager.AppSettings["uri"]);
instance.FactoryClient.Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(instance.FactoryClient.HeaderValue));
instance.FactoryClient.Client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue(instance.FactoryClient.Language));
instance.FactoryClient.Client.DefaultRequestHeaders.Remove("Authorization");
return instance.FactoryClient.Client;
}
}
public class AthenaFactoryHttpClient : ConfigurationElement
{
[ConfigurationProperty("headerValue", IsRequired = true)]
public string HeaderValue
{
get { return (string)base["headerValue"]; }
set { base["headerValue"] = value; }
}
[ConfigurationProperty("language", IsRequired = true)]
public string Language
{
get { return (string)base["language"]; }
set { base["language"] = value; }
}
public HttpClient Client { get; set; }
}
}
我这样打电话给我的客户:
private HttpClient client = AthenaHttpClients.GetClient();
这是我对后端服务器的一次调用:
internal HttpResponseMessage getStudyContract(string id)
{
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", (string)HttpContext.Current.Session["accessToken"]);
HttpResponseMessage response = client.GetAsync(restEndpoint + restStudyContractsEndpoint + "/" + id).Result;
return response;
}
catch (AggregateException ex)
{
throw new RestHttpClientRequestException(restRequestExceptionMessage, ex.StackTrace);
}
catch (Exception ex)
{
throw new RestHttpClientRequestException(ex.Message, ex.StackTrace);
}
}
(我知道它不是使用带有.Result的异步方法的最佳实现,但现在可以了)。我通过发送带有空字符串的Id强制我的请求getStudyContract()失败。然后我得到AggregateException,然后对我的客户端的所有后续调用都会丢失Accept和Accept-Language。我不知道自己做错了什么。如果有人有任何建议,请帮忙!