【发布时间】:2019-12-26 02:56:01
【问题描述】:
我人生中第一次尝试切换到 Linux,但我在那里的 C# 应用程序有点挣扎。
我正在制作一个应用程序,它每 60 秒抓取一次网站,将整个 html 代码保存在一个名为“original”的变量中,然后在每次运行后进行比较。如果网站的 html 代码有任何变化,它会向我的 Telegram 聊天发送一条消息,说“Hello world”。
我已经删除了我的凭据和资料,但这就是代码的样子。由于 .NET Core 2.2 中不存在 HttpClient(这是迄今为止我能够在 Linux 上安装的唯一一个(Ubuntu,我在 AWS EC2 和带有 XFCE 的远程桌面上)。我对 Linux 也完全陌生。我确实看到 .NET Core 3 已经发布,但我似乎无法安装它(我做错了什么吗?)。我也不知道 HttpClient 是否包含在其中。
无论如何;有什么方法可以用其他东西代替 HttpClient 来将我的 PostAsync 发送到 Telegram 的 API?
using System;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net;
using System.Collections.Generic;
namespace MyApp
{
class Program
{
private static readonly HttpClient httpclient = new HttpClient();
private static readonly WebClient client = new WebClient();
public static string original = "";
static void Main(string[] args)
{
Task.Run(async () =>
{
while (true)
{
await Task.Delay(60000);
string result = client.DownloadString("https://website.com");
if (original != result && original != "")
{
Dictionary<string, string> inputData = new Dictionary<string, string>
{
{ "chat_id", "x" },
{ "text", "Hello world" }
};
var request = await httpclient.PostAsync("https://api.telegram.org/botxxxx/sendMessage", new FormUrlEncodedContent(inputData));
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Apartment listings were updated.");
}
else
{
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " No change in apartment listings.");
}
original = result;
}
});
Console.Read();
}
}
}
错误信息:
Program.cs(5,18): error CS0234: The type or namespace name `Http' does not exist in the namespace `System.Net'. Are you missing `System.Net.Http' assembly reference?
Program.cs(21,33): error CS0246: The type or namespace name `HttpClient' could not be found. Are you missing an assembly reference?
Compilation failed: 2 error(s), 0 warnings
我只是用mcs Program.cs编译然后用mono Program.exe运行它
编辑:
解决方案:我不必构建它。我可以使用以下命令简单地运行它(无需对上述代码进行任何更改):dotnet run
效果很好!
【问题讨论】:
标签: c# .net linux post httpclient