自訂 HttpMessage Handler
class MyMessageHandler1 : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Console.WriteLine("MyMessageHandler - 準備要執行");
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
Console.WriteLine($"MyMessageHandler - 執行完畢,狀態碼為 {response.StatusCode}");
return response;
}
}
class MyMessageHandler2 : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Console.WriteLine("MyMessageHandler2 - 準備要執行");
request.Headers.TryAddWithoutValidation("APIKey", Global.APIKey);
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
Console.WriteLine($"MyMessageHandler2 - 執行完畢,狀態碼為 {response.StatusCode}");
return response;
}
}
使用自訂 HttpMessage Handler
private static async Task<APIResult> HttpGetAsync()
{
APIResult fooAPIResult;
using (HttpClientHandler handler = new HttpClientHandler())
{
var handler1 = new MyMessageHandler1();
var handler2 = new MyMessageHandler2();
handler1.InnerHandler = handler2;
handler2.InnerHandler = handler;
using (HttpClient client = new HttpClient(handler1))
{
try
{
#region 呼叫遠端 Web API
string FooUrl = $"http://vulcanwebapi.azurewebsites.net/api/values/CustHandler";
HttpResponseMessage response = null;
#region 設定相關網址內容
var fooFullUrl = $"{FooUrl}";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response = await client.GetAsync(fooFullUrl);
#endregion
#endregion
#region 處理呼叫完成 Web API 之後的回報結果
if (response != null)
{
if (response.IsSuccessStatusCode == true)
{
var fooCT = response.Headers.FirstOrDefault(x => x.Key == "APIKeyEcho");
var fooCT2 = fooCT.Value.FirstOrDefault();
Console.WriteLine($"APIKeyEcho={fooCT2}");
String strResult = await response.Content.ReadAsStringAsync();
fooAPIResult = JsonConvert.DeserializeObject<APIResult>(strResult, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore });
}
else
{
fooAPIResult = new APIResult
{
Success = false,
Message = string.Format("Error Code:{0}, Error Message:{1}", response.StatusCode, response.RequestMessage),
Payload = null,
};
}
}
else
{
fooAPIResult = new APIResult
{
Success = false,
Message = "應用程式呼叫 API 發生異常",
Payload = null,
};
}
#endregion
}
catch (Exception ex)
{
fooAPIResult = new APIResult
{
Success = false,
Message = ex.Message,
Payload = ex,
};
}
}
}
return fooAPIResult;
}
觸發的 Web API 動作
[HttpGet("CustHandler")]
public APIResult CustHandler()
{
APIResult foo;
StringValues VerifyCode = "";
this.HttpContext.Request.Headers.TryGetValue("APIKey", out VerifyCode);
if (StringValues.IsNullOrEmpty(VerifyCode))
{
foo = new APIResult()
{
Success = false,
Message = "API 金鑰 沒有發現",
Payload = null
};
Request.HttpContext.Response.Headers.Add("APIKeyEcho", "No API Key");
}
else
{
if (VerifyCode != "123")
{
foo = new APIResult()
{
Success = false,
Message = "API 金鑰 不正確",
Payload = null
};
Response.Headers.Add("APIKeyEcho", "API Key is incorrect");
}
else
{
foo = new APIResult()
{
Success = true,
Message = "API 金鑰 正確無誤",
Payload = null
};
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(VerifyCode);
string echo = Convert.ToBase64String(bytes);
Request.HttpContext.Response.Headers.Add("APIKeyEcho", echo);
}
}
return foo;
}
進行測試
static async Task Main(string[] args)
{
var foo = await HttpGetAsync();
Console.WriteLine($"使用 Get 方法呼叫 Web API 的結果");
Console.WriteLine($"結果狀態 : {foo.Success}");
Console.WriteLine($"結果訊息 : {foo.Message}");
Console.WriteLine($"");
Console.WriteLine($"Press any key to Exist...{Environment.NewLine}");
Console.ReadKey();
}
執行結果
MyMessageHandler - 準備要執行
MyMessageHandler2 - 準備要執行
MyMessageHandler2 - 執行完畢,狀態碼為 OK
MyMessageHandler - 執行完畢,狀態碼為 OK
APIKeyEcho=MTIz
使用 Get 方法呼叫 Web API 的結果
結果狀態 : True
結果訊息 : API 金鑰 正確無誤
Press any key to Exist...
HTTP 傳送與接收原始封包
GET http://vulcanwebapi.azurewebsites.net/api/values/CustHandler HTTP/1.1
Accept: application/json
APIKey: 123
Host: vulcanwebapi.azurewebsites.net
Connection: Keep-Alive
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Server: Kestrel
APIKeyEcho: MTIz
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=4cbc3e777eee0146fcbb9f695794b29417cc953731f6f8f581457a1d7cd7aa14;Path=/;HttpOnly;Domain=vulcanwebapi.azurewebsites.net
Date: Sun, 29 Oct 2017 06:38:07 GMT
43
{"success":true,"message":"API 金鑰 正確無誤","payload":null}
0
相關文章索引