简体   繁体   中英

Can't return HTTP status and data from a method after using httpClient.GetAsync()

I am having issues with the following code. I am retrieving a JSON object as a string and then wish to return this from my method so it can be used elsewhere. When I do however I get the message:

'filmsGlossary.searchQueries.returnJson(object); returns void, a return keyword must not be followed by an object expression'

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)
        {

        }
}

Originally I was only returning

return content;

However after reading it seemed that the issue might be that I needed to change this to:

return content.ToString();

However this did not help. I also read that I could change it to a synchronous, rather than asynchronous method and change the method to be 'public string' however I am only just learning c# and don't yet fully understand the implications of this (or how to do it).

Is it possible to resolve this error within the code I already have?

I would also like to understand the cause of the issue rather than just know the solution.

Thanks.

You really should paste the error messages that you are getting.

Why does your function declaration return void ? It should return Task< string >.

public async Task<string> returnJson(object term)

Also in the body you should return the Task, like this:

await response.Content.ReadAsStringAsync();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM