[英]HttpClient GetAsync not working as expected
當用 Postman 測試我的 web API 時,我的 API 執行得很好!
當涉及到在我的客戶端應用程序中使用HttpClient
運行代碼時,代碼執行時沒有錯誤,但在服務器上沒有預期的結果。 會發生什么?
從我的客戶端應用程序:
private string GetResponseFromURI(Uri u)
{
var response = "";
HttpResponseMessage result;
using (var client = new HttpClient())
{
Task task = Task.Run(async () =>
{
result = await client.GetAsync(u);
if (result.IsSuccessStatusCode)
{
response = await result.Content.ReadAsStringAsync();
}
});
task.Wait();
}
return response;
}
這是 API controller:
[Route("api/[controller]")]
public class CartsController : Controller
{
private readonly ICartRepository _cartRepo;
public CartsController(ICartRepository cartRepo)
{
_cartRepo = cartRepo;
}
[HttpGet]
public string GetTodays()
{
return _cartRepo.GetTodaysCarts();
}
[HttpGet]
[Route("Add")]
public string GetIncrement()
{
var cart = new CountedCarts();
_cartRepo.Add(cart);
return _cartRepo.GetTodaysCarts();
}
[HttpGet]
[Route("Remove")]
public string GetDecrement()
{
_cartRepo.RemoveLast();
return _cartRepo.GetTodaysCarts();
}
}
請注意,這些 API 調用在從 Postman 調用時按預期工作。
您不應該使用await with client.GetAsync,它由.Net平台管理,因為您當時只能發送一個請求。
就像這樣使用它
var response = client.GetAsync("URL").Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
// Parse the response body. Blocking!
var dataObjects = response.Content.ReadAsAsync<object>().Result;
}
else
{
var result = $"{(int)response.StatusCode} ({response.ReasonPhrase})";
// logger.WriteEntry(result, EventLogEntryType.Error, 40);
}
你正在做一場“一勞永逸”的做法。 在您的情況下,您需要等待結果。
例如,
static async Task<string> GetResponseFromURI(Uri u)
{
var response = "";
using (var client = new HttpClient())
{
HttpResponseMessage result = await client.GetAsync(u);
if (result.IsSuccessStatusCode)
{
response = await result.Content.ReadAsStringAsync();
}
}
return response;
}
static void Main(string[] args)
{
var t = Task.Run(() => GetResponseFromURI(new Uri("http://www.google.com")));
t.Wait();
Console.WriteLine(t.Result);
Console.ReadLine();
}
用於獲取頁面數據的簡單示例。
public string GetPage(string url)
{
HttpResponseMessage response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
string page = response.Content.ReadAsStringAsync().Result;
return "Successfully load page";
}
else
{
return "Invalid Page url requested";
}
}
使用httpclient時,我遇到了chace控件的問題。
HttpBaseProtocalFilter^ filter = ref new HttpBaseProtocolFilter();
filter->CacheControl->ReadBehavior = Windows::Web::Http::Filters::HttpCacheReadBehavior::MostRecent;
HttpClient^ httpClient = ref new HttpClient(filter);
我不確定預期的結果是什么,或者你得到什么結果,所以這真的只是一個猜謎游戲。
當我使用HttpClient發布一些內容時,我發現手動添加標題似乎比使用默認標頭更常用。
auto httpClient = ref new HttpClient();
Windows::Web::Http::Headers::HttpMediaTypeHeaderValue^ type = ref new Windows::Web::http::Headers::HttpMediaTypeHeaderValue("application/json");
content->Headers->ContentType = type;
如果我不做這兩件事我發現,對我來說,無論如何,我的網絡請求的一半時間實際上並沒有被發送,或者標題都搞砸了,而另一半時間它完美地工作了。
我只是讀了一條評論,你說它只會觸發一次,這讓我覺得它是緩存控制。 我認為會發生什么事情(Windows?)看到發送的2個請求是完全相同的,所以為了加快速度,它只是假設相同的答案,並且從未實際發送第二次請求
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.