c# - .NET Core 2.2 中的 HttpClient 等价物?
问题描述
我刚刚尝试在我的生命中第一次切换到 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
构建项目(检查您是否在项目目录中)
推荐阅读
- email - woocommerce 中是否有过滤器或挂钩来更改 WC_Tax::get_rate_label( $key )?
- javascript - 在 redux 中使用 react 路由器
- jquery - 我如何隐藏和显示表单使用 jquery
- ruby - Ruby 生成带有句点属性的 XML 文档
- java - 索引 3 超出长度 3 的范围
- mysql - 如何在 mysql 和 php 中检查早于某个日期的帐户?
- typescript - tsc 和嵌套的 tsconfigs
- django - 为 Django 认证的 API 视图编写测试用例
- scroll - 嵌套 SingleChildScrollView
- julia - y=1/x 的 Julia MethodError