我正在尝试调用简单的POST API,以通过Console App创建Zendesk Ticket。我在VS2019中创建了C#核心控制台应用程序,并粘贴了应该创建New Ticket的简单代码。代码可以在其他应用程序中工作,但在控制台应用程序中,该应用程序只是从调试中注销...电话永远不会过去...
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://testhelp.zendesk.com/api/v2/tickets.json"))
{
try
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("[email protected]:testPassword"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("{\"ticket\": {\"subject\": \"My first Ticket!\", \"comment\": { \"body\": \"The ticket is from API.\" }}}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
Console.WriteLine(response);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
我想念的是什么?
我的猜测是,通过异步调用,您的程序在控制台版本中就已经结束了。
通过在主要方法中进行一次简单的等待即可解决?
static void Main(string[] args)
{
var t = new Task(createTicket);
t.Start();
while(! t.IsCompleted) //IsCompleted is probably not robust enough but you can see if your call ever finishes this way
{
System.Threading.Thread.Sleep(100);
}
}
async static void createTicket()
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://testhelp.zendesk.com/api/v2/tickets.json"))
{
try
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("[email protected]:testPassword"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("{\"ticket\": {\"subject\": \"My first Ticket!\", \"comment\": { \"body\": \"The ticket is from API.\" }}}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
Console.WriteLine(response);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}