0
我想要一個通用函數,它將發送一個http請求&返回一個HttpResponseMessage。 這是我現在得到的。HttpClient檢索Web API響應
public static HttpResponseMessage SendRequest(string actionUri, string baseAddress, HttpRequestMessage request)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseAddress);
HttpResponseMessage response = null;
foreach (var header in request.Headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
if (request.Method == HttpMethod.Get)
{
response = client.GetAsync(actionUri).Result;
}
if (request.Method == HttpMethod.Post)
{
response = client.PostAsync(actionUri, request.Content).Result;
}
if (request.Method == HttpMethod.Put)
{
response = client.PutAsync(actionUri, request.Content).Result;
}
if (request.Method == HttpMethod.Delete)
{
response = client.DeleteAsync(actionUri).Result;
}
return response;
}
}
以上功能可以寫成下面
public static HttpResponseMessage SendRequest1(string actionUri, string baseAddress, HttpRequestMessage request)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseAddress);
return client.SendAsync(request).Result;
}
}
是否有使用第二種方法與基於HTTP動詞的顯式調用的任何問題。對於一些請求,我收到GET請求的錯誤爲「無法使用此動詞類型發送內容主體」