尝试从 VS2019 中的控制台应用程序调用简单的 POST API [英] Trying to call simple POST API from console App in VS2019

查看:40
本文介绍了尝试从 VS2019 中的控制台应用程序调用简单的 POST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调用简单的 POST API 从控制台应用程序创建一个 Zendesk 票证.我在 VS2019 中创建了 C# 核心控制台应用程序并粘贴了应该创建新票证的简单代码.代码在其他应用程序中工作,但在控制台应用程序中,应用程序只需从调试中注销...
电话永远不会...

using (var httpClient = new HttpClient()){使用 (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://testhelp.zendesk.com/api/v2/tickets.json")){尝试{var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("test@test.com:testPassword"));request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");request.Content = new StringContent("{\"ticket\": {\"subject\": \"My first Ticket!\", \"comment\": { \"body\": \"门票来自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(响应);}捕获(异常前){Console.WriteLine(ex);}}}

我错过了什么?

解决方案

异步调用在某些情况下是冷酷的情妇.

一个不错的选择是使您的主程序异步,因此能够等待任务.这里的问题是 GUI,如果那是您离开命令行时实际拥有的东西,我不确定它与 UI 线程的配合效果如何,但这是示例.哪个更优雅.

<预><代码>静态异步任务 Main(string[] args){var TicketTask = await createTicket();}异步静态任务<字符串>创建票证(){var content =未知错误";使用 (var httpClient = new HttpClient()){使用 (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://testhelp.zendesk.com/api/v2/tickets.json")){尝试{var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes(test@test.com:testPassword"));request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");request.Content = new StringContent("{\"ticket\": {\"subject\": \"My first Ticket!\", \"comment\": { \";body\": \"票据来自 API.\" }}}");request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(application/json");ServicePointManager.Expect100Continue = true;ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);//Console.WriteLine(响应);}捕获(异常前){内容 = ex.Message;}}}返回内容;}

快速而肮脏的简单解决方案(我不建议用于生产)是将主循环中的内容作为全局变量进行监控,您可以在成功或失败时填充它.

 静态字符串内容 = ";static void Main(string[] args){var 循环计数 = 0;var t = 新任务(createTicket);t.开始();while(content == ""; && loopcount < 50000){System.Threading.Thread.Sleep(100);循环计数++;}}异步静态无效 createTicket(){使用 (var httpClient = new HttpClient()){使用 (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://testhelp.zendesk.com/api/v2/tickets.json")){尝试{var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("test@test.com:testPassword"));request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");request.Content = new StringContent("{\"ticket\": {\"subject\": \"My first Ticket!\", \"comment\": { \";body\": \"票据来自 API.\" }}}");request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(application/json");ServicePointManager.Expect100Continue = true;ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);//Console.WriteLine(响应);}捕获(异常前){内容 = ex.message;}}}}

I am trying to call simple POST API to create a Zendesk Ticket from Console App. I create C# core console app in VS2019 and pasted simple code which should create New Ticket. code work in other app but in console app, app just log out from debug...
call never goes...

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("test@test.com: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);
        }
    }
}

What am I missing?

解决方案

Async calls are frigid mistresses in some cases.

A good option is to make your main program async and therefore able to await tasks. The issue here is with GUI if that is what you actually have when you get away from the command line I am not sure how well it plays with UI threads, but here is the example. Which is much more elegant.


        static async Task Main(string[] args)
            {
                 var  TicketTask = await createTicket();
            }
        
             async static Task<string> createTicket()
            {
                var content = "unknown error";
                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("test@test.com: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);
                            content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                            //Console.WriteLine(response);
                        }
                        catch (Exception ex)
                        {
                            content = ex.Message;
                        }
                    }
                }
                return content;
            }

Quick-and-dirty-simple-solution (which I would not suggest for production) is to monitor content within the main loop as a global variable where you fill it on success or failure.

      static string content = "";
        static void Main(string[] args)
        {
            var loopcount = 0;
            var t = new Task(createTicket);
            t.Start();
            while(content == "" && loopcount < 50000)
            {
                System.Threading.Thread.Sleep(100);
                loopcount++;
            }
        }
    
         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("test@test.com: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);
                        content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        //Console.WriteLine(response);
                    }
                    catch (Exception ex)
                    {
                        content = ex.mesage;
                    }
                }
            }
        }

这篇关于尝试从 VS2019 中的控制台应用程序调用简单的 POST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆