我一生中第一次尝试切换到 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
工作得很好!
最佳答案
正如 TheYellowSquares 提到的,HttpClient 确实存在于 .Net Core 2.2 中(您可以在此处看到它,例如 https://github.com/dotnet/corefx/blob/1284396e317e5e7146135b0ba5088741705122e6/src/System.Net.Http/src/System/Net/Http/HttpClient.cs )唯一的事情是您不需要添加任何特定的包。
您发布的代码片段在 Windows 和 Linux 上编译时应该没有错误。只需使用命名空间 System.Net.Http(已在您的代码片段中)就足够了。
--更新
使用dotnet build
来构建项目(检查您是否在项目目录中)
关于c# - .NET Core 2.2 中的 HttpClient 等效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57581285/