[英]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.
我正在将JSON对象检索为字符串,然后希望从我的方法中返回它,以便可以在其他地方使用。 When I do however I get the message:
但是,当我这样做时,会收到消息:
'filmsGlossary.searchQueries.returnJson(object); 'filmsGlossary.searchQueries.returnJson(object); returns void, a return keyword must not be followed by an object expression'
返回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)
{
}
}
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).
我还读到我可以将其更改为同步方法,而不是异步方法,并将该方法更改为“公共字符串”,但是我只是在学习c#,还没有完全理解此方法的含义(或方法) )。
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
? 为什么您的函数声明返回
void
? It should return Task< string
>. 它应该返回Task <
string
>。
public async Task<string> returnJson(object term)
Also in the body you should return the Task, like this: 同样,您应该在正文中返回Task,如下所示:
await response.Content.ReadAsStringAsync();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.