.Net Core 控制台应用程序中的 Http 侦听器?

Http Listener in .Net Core console app?

我开始研究 .net Core,但我有点迷路了。

我正在尝试创建一个接受 Http 请求的控制台应用程序,例如 HttpListener,但它在 .net Core 上不存在。

我搜索了很多,只发现一些 post 提到它不存在。

所以,我的问题是,是否可以在 .net Core 控制台应用程序中接受 Http 请求?

如果是,类?

干杯。

要构建自托管 Web 应用程序,请通过 New Project -> Templates -> Web -> ASP.NET Core Web Application 在 VS2015 中使用已安装的模板。

此向导创建一个自承载的 Web 应用程序。从入口Main方法可以看到它使用WebHostBuilder,添加配置(特别是.UseKestrel表示web服务器),然后运行它。

除了模板,您还可以搭建自己的简单网络服务器。在Startup.cs中的Configure方法中,可以使用

app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello World!");
});

它允许您处理请求上下文并响应它。

有关详细信息,请查看 this article

我正在交叉链接到 2017 年 5 月 13 日的另一个答案,该答案似乎有关于此主题的更新答案:

据说要使用“.NET Core 2.0,它有一个 API compatible HttpListener 可以工作 cross-platform”

使用下面的代码:

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        const int timeoutInDays = 1;
        Stream dataStream;
        StreamReader reader;

        while(true)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.Timeout = TimeSpan.FromDays(timeoutInDays);

                dataStream = await httpClient.GetStreamAsync("https://localhost:5001/api/v1/customers/streaming");

                reader = new StreamReader(dataStream);
                Console.WriteLine(await reader.ReadLineAsync());
                reader.Close();
            }
        }
    }

}