使用httpClient.GetAsync()后无法从方法返回HTTP状态和数据

时间:2014-12-02 07:26:10

标签: c# dotnet-httpclient

我遇到以下代码问题。我正在检索一个JSON对象作为字符串,然后希望从我的方法返回它,以便它可以在别处使用。但是,当我这样做时,我收到了消息:

“filmsGlossary.searchQueries.returnJson(对象);返回void,返回关键字后面不能跟一个对象表达式'

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#并且还没有完全理解它的含义(或者如何做到这一点) )。

是否可以在我已有的代码中解决此错误?

我还想了解问题的原因,而不仅仅是了解解决方案。

感谢。

1 个答案:

答案 0 :(得分:2)

你真的应该粘贴你得到的错误信息。

为什么函数声明会返回void?它应该返回任务< string>。

public async Task<string> returnJson(object term)

同样在正文中你应该返回任务,如下所示:

await response.Content.ReadAsStringAsync();