[英]ASP.NET HTTPClient Get request status waiting for activation
I am writing a method that will return JSON data by making a GET request to a RestApi URL. 我正在编写一个通过向RestApi URL发出GET请求来返回JSON数据的方法。 When I run the application in debug mode, I get below data in response. 当我在调试模式下运行应用程序时,得到以下数据作为响应。
Id = 337, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"
Here is my code: 这是我的代码:
public class Methods
{
public static async Task<JObject> Get(string url, string username, string password)
{
var credentials = new NetworkCredential(username, password);
HttpClientHandler handler = new HttpClientHandler { Credentials = credentials };
HttpClient client = new HttpClient(handler);
// client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
return JObject.Parse(await response.Content.ReadAsStringAsync());
}
return new JObject { response.StatusCode };
}
}
Here is my view where I am trying to access data: 这是我尝试访问数据的视图:
public IActionResult Index()
{
// Methods RestMethod = new Methods();
var data = Methods.Get("http://url/products", "domain\userid", "Password");
return View();
}
When I add debug in view at var data = .....
thats where I am getting waiting for activation
. 当我在var data = .....
视图中添加debug时,这就是我要waiting for activation
。
Any help is really appreciated. 任何帮助都非常感谢。 :) :)
Thanks, 谢谢,
Ray 射线
If you are going to use async/await you should do it starting from the calling entry point. 如果要使用异步/等待,则应从调用入口点开始。 Currently you call the Get
method which returns a running task but you do not wait for it to be completed. 当前,您调用Get
方法,该方法返回正在运行的任务,但是您不等待它完成。 The easiest fix is for your Index
method code should be changed like so: 最简单的解决方法是更改Index
方法代码,如下所示:
public async Task<IActionResult> Index()
{
// Methods RestMethod = new Methods();
var data = await Methods.Get("http://url/products", "domain\userid", "Password");
return View();
}
Also see Stephen Cleary's blog for more details on async/await
, he has written extensively on on this subject and also well known pitfalls and patterns. 另请参阅Stephen Cleary的博客 ,了解有关async/await
更多详细信息,他已就该主题以及众所周知的陷阱和模式进行了广泛的写作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.