我从基于UWP的较新应用程序开发开始。在编写http请求客户端时,我注意到我的大多数请求都需要使用Authorization
标头。因此,我实现/复制了the MSDN docs中提供的示例插件过滤器。
现在,我在基本的HTTP客户端类中有2个方法,一个使用在使用上述过滤器的情况下创建的static / singleton客户端,另一个在每次调用时都创建一个新的HttpClient
首次登录)。
我计划使用第一次登录方法,以防授权令牌在我的过滤器中过期。为此,我天真的实现了一个do-while循环:
// The following snippet is from the IHttpFilter implementation
public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
{
return AsyncInfo.Run<HttpResponseMessage, HttpProgress>(async (cancellation, progress) =>
{
int retries = 0;
HttpResponseMessage response;
do
{
string authToken = UserSettings.Instance.AccessToken;
request.Headers.Authorization = HttpCredentialsHeaderValue.Parse($"Bearer {authToken}");
response = await baseFilter.SendRequestAsync(request).AsTask(cancellation, progress);
if (!response.IsSuccessStatusCode && response.StatusCode == HttpStatusCode.Unauthorized)
{
new AuthClient().GenerateAccessToken(AuthGrantType.REFRESH);
}
} while (response.StatusCode == HttpStatusCode.Unauthorized && ++retries < 3);
cancellation.ThrowIfCancellationRequested();
return response;
});
}
在这里,我的AuthClient.GenerateAccessToken
负责更新UserSettings
惰性实例。
这个do-while
块能够更新authToken
的值,以防旧值过期,但是当它再次返回循环时,会引发以下异常:
An exception of type 'System.InvalidOperationException' occurred in System.Private.CoreLib.dll but was not handled in user code
A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)
我了解我之前的任务已被缓存,并且由于我在第一次运行中await
将其缓存,因此任务已结束。
如果令牌过期,我应该如何实现重新登录的逻辑?是否应该放置另一个仅处理response.StatusCode == Unauthorized
情况的过滤器?对于这种模式还有什么建议?