-
Notifications
You must be signed in to change notification settings - Fork 446
/
Copy pathAuthorizationHandler.cs
65 lines (61 loc) · 2.65 KB
/
AuthorizationHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System.ComponentModel;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace WebApiClientCore.HttpMessageHandlers
{
/// <summary>
/// 表示授权应用的抽象 http 消息处理程序
/// </summary>
public abstract class AuthorizationHandler : DelegatingHandler
{
/// <summary>
/// 检测响应是否未授权
/// 未授权则重试请求一次
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[EditorBrowsable(EditorBrowsableState.Never)]
protected sealed override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await this.SendAsync(SetReason.ForSend, request, cancellationToken).ConfigureAwait(false);
if (await this.IsUnauthorizedAsync(response).ConfigureAwait(false) == true)
{
response = await this.SendAsync(SetReason.ForResend, request, cancellationToken).ConfigureAwait(false);
}
return response;
}
/// <summary>
/// 发送请求
/// </summary>
/// <param name="reason">原因</param>
/// <param name="request">请求消息</param>
/// <param name="cancellationToken">取消令牌</param>
/// <returns></returns>
private async Task<HttpResponseMessage> SendAsync(SetReason reason, HttpRequestMessage request, CancellationToken cancellationToken)
{
await this.SetAuthorizationAsync(reason, request, cancellationToken).ConfigureAwait(false);
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// 设置请求的授权信息
/// </summary>
/// <param name="reason">授权原因</param>
/// <param name="request">请求消息</param>
/// <param name="cancellationToken">取消令牌</param>
/// <returns></returns>
protected abstract Task SetAuthorizationAsync(SetReason reason, HttpRequestMessage request, CancellationToken cancellationToken);
/// <summary>
/// 返回响应是否为未授权状态
/// 反回 true 则触发重试请求
/// </summary>
/// <param name="response">响应消息</param>
protected virtual Task<bool> IsUnauthorizedAsync(HttpResponseMessage response)
{
var state = response != null && response.StatusCode == HttpStatusCode.Unauthorized;
return Task.FromResult(state);
}
}
}