C# .net核心控制台方法调用
我试图从.net core控制台应用程序的Main()方法调用一个方法,该方法应显示外部api的两个属性,但控制台仅显示Hello World,而不显示其他结果数据,我还希望控制台保持不变,不从屏幕上消失。欢迎提供所有帮助,并提前向您表示感谢 UserItem.cs-C# .net核心控制台方法调用,c#,rest,asp.net-core,console-application,C#,Rest,Asp.net Core,Console Application,我试图从.net core控制台应用程序的Main()方法调用一个方法,该方法应显示外部api的两个属性,但控制台仅显示Hello World,而不显示其他结果数据,我还希望控制台保持不变,不从屏幕上消失。欢迎提供所有帮助,并提前向您表示感谢 UserItem.cs- public class UserItem { public UserItem(string name, string url) { Name = name; Url = url;
public class UserItem
{
public UserItem(string name, string url)
{
Name = name;
Url = url;
}
public string Name { get; set; }
public string Url { get; set; }
}
Program.cs-
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
GetUser();
}
// retrieve all.
public static async void GetUser()
{
//baseUrl
string baseUrl = "http://pokeapi.co/api/v2/pokemon/";
try
{
// HttpClient implements a IDisposable interface.
using (HttpClient client = new HttpClient())
{
//initiate Get Request (await will execute the using statement in order).
using (HttpResponseMessage res = await client.GetAsync(baseUrl))
{
//get content from response, then convert it to a c# object.
using (HttpContent content = res.Content)
{
//assign content to data variable by converting into a string using await.
var data = await content.ReadAsStringAsync();
//If the data is not null log convert the data using newtonsoft JObject Parse class method.
if (content != null)
{
//log data object in the console
Console.WriteLine("data------------{0}", JObject.Parse(data)["results"]);
}
else
{
Console.WriteLine("NO Data----------");
}
}
}
}
}
catch (Exception exception)
{
Console.WriteLine("Exception Hit------------");
Console.WriteLine(exception);
}
}
}
async void
被触发并遗忘,您的主应用程序将继续执行,从main
返回并终止,很可能在异步任务完成之前。相反,使用async Task
作为您的方法,并在Main
中等待它(提示,如果您使用的是最新的编译器,您也可以将Main设置为async Task
),至于在应用程序终止之前暂停,请放置控制台。ReadLine()代码>在Main(…)
的末尾。完成后,将输出张贴在此处。@LasseVågsætherKarlsen:您应该将其作为答案张贴。始终等待异步内容,除非您确切知道为什么不等待,并且完全理解不等待的含义(即,您正在做出明智的决定,不等待是为了一个非常特定的目的)。您需要执行static async Task Main()
(我删除了args参数,因为您似乎没有使用它,但如果需要,可以随意添加它),然后您可以等待GetUser
(使GetUser返回任务后),在这里一切正常的情况下,当移动到服务中执行的生产就绪代码时,使用(HttpClient)
实际上是一种反模式。请稍后记住。因为问题是关于.NET Core的,OP可以使用C#7,它为Main添加了异步支持
using System;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//Waits the API response
GetUser().Wait();
//Waits until a key is pressed.
Console.ReadKey();
}
// retrieve all.
public static async Task GetUser()
{
//...
}
}
}