首页 > 解决方案 > 使用 HttpClient 时收到无效参数

问题描述

我正在尝试在控制台应用程序中获取 web api 数据。接收数据正常工作,直到我尝试将其他名为“Nsi”的库中的其他类连接到应用程序。因此,接收数据失败并出现 Invalid argument received 错误。更改库名称可解决该错误。所有的库都建立在 Net5 平台上

链接到示例项目 https://drive.google.com/drive/folders/1wftAzUWqtEefdv2vWiOwzuNGHBvmehG9?usp=sharing

控制台应用程序:

static void Main(string[] args)
{
    var httpServices = new ServiceCollection();

    httpServices.AddHttpClient<IHttpService, HttpService>();

    httpServices.AddTransient<ITest, Test>(); 

    var httpServiceProvider = httpServices.BuildServiceProvider();

    var client = httpServiceProvider.GetRequiredService<IHttpService>();

    var ss = client.Get("https://www.google.com/");

    Console.Write(ss);
}

插件类:

public class HttpService : IHttpService
{
    private readonly HttpClient Client;
    public HttpService(HttpClient httpClient)
    {
        Client = httpClient;
    }

    public string Get(string url)
    {
        return Client.GetStringAsync(url).Result;
    }
}

public interface IHttpService
{
    public string Get(string url);
}

此类已放置在单独的库“Nsi”中:

public interface ITest
{
    void TestMethod();
}

public class Test : ITest
{
    public void TestMethod()
    {
    }
}

错误 “发生一个或多个错误。(收到的参数无效。(www.google.com:443))”

标签: c#httpclient.net-5

解决方案


推荐阅读