C# HttpClient GetAsync失败
我一直在尝试构建一个Windows控制台PP作为Web服务运行,以来回同步一些数据。我已经构建了一个用于同步的项目,当我在wpf项目中运行它时,它似乎可以工作,但不能C# HttpClient GetAsync失败,c#,web-services,asp.net-web-api,httpclient,C#,Web Services,Asp.net Web Api,Httpclient,我一直在尝试构建一个Windows控制台PP作为Web服务运行,以来回同步一些数据。我已经构建了一个用于同步的项目,当我在wpf项目中运行它时,它似乎可以工作,但不能 using System; using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using System.Net.Http.Headers; using QAQC_DataCommon.Models; namespa
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using QAQC_DataCommon.Models;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
Gettasks();
}
public static async void Gettasks()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost/QAQC_SyncWebService/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
var response = await client.GetAsync("Tasks/?username=XXXXXX&LastUpdated=1/1/15");
if (response.IsSuccessStatusCode)
{
List<QaqcRow> ls = await response.Content.ReadAsAsync<List<QaqcRow>>();
foreach (QaqcRow qaqcRow in ls)
{
Debug.WriteLine(qaqcRow.GetValue("BusinessUnit"));
}
}
}
catch (Exception)
{
throw;
}
}
}
}
我的Web服务中的控制器如下所示:
public IEnumerable<QaqcRow> Index(string username, string lastUpdated)
{
return GetFilteredList(username, lastUpdated).OrderBy(x => x.GetValue("FormId"));
}
public IEnumerable索引(字符串用户名,字符串lastUpdated)
{
返回GetFilteredList(用户名,LastUpdate).OrderBy(x=>x.GetValue(“FormId”);
}
我可以通过链接手动转到Web服务并获取数据,但当我使用httpclient时,它就死了。我想它不会等待执行结束,因此会过早退出程序。(参见示例) 改变
public static async void Gettasks()
到
然后等待执行结束
static async void Main(string[] args)
{
await Gettasks();
}
编辑:啊,原来Main
不能是异步的。因此,现在可能只是通过阻塞线程来确认正确调用了这个方法get,直到结束
static void Main(string[] args)
{
Gettasks();
Console.ReadLine(); //just don't press enter immedietly :)
}
主方法不能是
async
.Oops,不经思考就发布。您应该仍然能够将其包装为任务
或其他内容。我添加了一个变通方法。或者您可以执行Gettasks().Wait()
。在main
方法中这样做是可以的。谢谢,就是这样。看来我需要复习一下我的asyc。
static async void Main(string[] args)
{
await Gettasks();
}
static void Main(string[] args)
{
Gettasks();
Console.ReadLine(); //just don't press enter immedietly :)
}