我在从.net核心发出Odata请求时添加了令牌,如下所示:
var settings = new ODataClientSettings(new Uri(AppConstants.BaseLink));
settings.BeforeRequestAsync += async (HttpRequestMessage message) =>
{
var token = await _tokenService.GetCRMTokenAsync();
message.Headers.Authorization = new AuthenticationHeaderValue(token.TokenType, token.AccessToken);
};
现在,我想添加一个拦截器,即当有未经授权的响应时,我想拦截该响应,获取新令牌并再次发送请求。
我写了这样的东西:
settings.AfterResponseAsync += async (HttpResponseMessage response) =>
{
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
var token = await _tokenService.GetCRMTokenAsync();
await _tokenService.RefreshCRMTokenAsync(token.RefreshToken);
HttpRequestMessage msg = new HttpRequestMessage();
msg = response.RequestMessage;
response = null;
msg.Headers.Authorization = new AuthenticationHeaderValue(token.TokenType, "");
var client = _httpClientFactory.CreateClient();
await client.SendAsync(msg);
}
};
但是以上方法不起作用。有谁知道如何使这项工作,或以其他方式实现这一目标。预先感谢。