![](/img/trans.png)
[英]How to determine a 404 response status when using the HttpClient.GetAsync()
[英]Can't return HTTP status and data from a method after using httpClient.GetAsync()
我的以下代碼有問題。 我正在將JSON對象檢索為字符串,然后希望從我的方法中返回它,以便可以在其他地方使用。 但是,當我這樣做時,會收到消息:
'filmsGlossary.searchQueries.returnJson(object); 返回void,return關鍵字后面不能緊跟對象表達式”
public async void returnJson(object term)
{
//Set Variables
var searchFormat = "&format=json";
var termValue = term;
var httpClient = new HttpClient();
try
{
//Set web service URL format
string baseURI = "http://localhost/filmgloss/webService/web-service.php?termName=";
string userURI = baseURI + termValue + searchFormat;
//Send URL to web service and retrieve response code.
var response = await httpClient.GetAsync(userURI);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
return content.ToString();
}
catch (HttpRequestException hre)
{
}
catch (Exception ex)
{
}
}
本來我只是回來
return content;
但是,在閱讀之后,似乎是我需要將其更改為:
return content.ToString();
但是,這沒有幫助。 我還讀到我可以將其更改為同步方法,而不是異步方法,並將該方法更改為“公共字符串”,但是我只是在學習c#,還沒有完全理解此方法的含義(或方法) )。
是否可以在我已有的代碼中解決此錯誤?
我還想了解問題的原因,而不僅僅是了解解決方案。
謝謝。
您確實應該粘貼收到的錯誤消息。
為什么您的函數聲明返回void
? 它應該返回Task < string
>。
public async Task<string> returnJson(object term)
同樣,您應該在正文中返回Task,如下所示:
await response.Content.ReadAsStringAsync();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.