我正在编写一个方法,通过向RestApi URL发出GET请求来返回JSON数据。当我在调试模式下运行应用程序时,我会在响应中得到以下数据。
Id = 337, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"
这是我的代码:
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 };
}
}
以下是我在尝试访问数据的视图:
public IActionResult Index()
{
// Methods RestMethod = new Methods();
var data = Methods.Get("http://url/products", "domain\userid", "Password");
return View();
}
当我在var data = .....
视图中添加调试时,我得到的地方waiting for activation
。
非常感谢任何帮助。 :)
谢谢,
雷
答案 0 :(得分:2)
如果你打算使用async / await,你应该从调用入口点开始。目前,您调用Get
方法,该方法返回正在运行的任务,但您不必等待它完成。最简单的解决方法是,Index
方法代码应该像这样更改:
public async Task<IActionResult> Index()
{
// Methods RestMethod = new Methods();
var data = await Methods.Get("http://url/products", "domain\userid", "Password");
return View();
}
另请参阅Stephen Cleary's blog了解有关async/await
的更多详情,他撰写了大量有关此主题以及众所周知的陷阱和模式的文章。