C# 我可以在不是ASP.NET core的.NET.core应用程序中使用HttpClientFactory吗?
我已经阅读了关于使用HttpClientFactory的热门博客文章C# 我可以在不是ASP.NET core的.NET.core应用程序中使用HttpClientFactory吗?,c#,asp.net-core,.net-core,httpclientfactory,C#,Asp.net Core,.net Core,Httpclientfactory,我已经阅读了关于使用HttpClientFactory的热门博客文章 ServiceCollection.AddScoped<HttpClient>(x => x.GetService<IHttpClientFactory>().CreateClient("yourClientName")); 引述 ASP.NET Core 2.1即将推出一项新的HttpClientFactory功能,这有助于解决开发人员在使用HttpClient实例从其应用程序发出外部web
ServiceCollection.AddScoped<HttpClient>(x =>
x.GetService<IHttpClientFactory>().CreateClient("yourClientName"));
引述
ASP.NET Core 2.1即将推出一项新的HttpClientFactory功能,这有助于解决开发人员在使用HttpClient实例从其应用程序发出外部web请求时可能遇到的一些常见问题
所有的例子都显示了在asp.net应用程序的启动类中连接它
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddHttpClient();
}
我的问题是你能在ASP.NET内核之外使用吗?
如果有,有没有例子
我原以为很多非web应用程序(.net core应用程序)需要进行web调用,那么为什么这不是.net core api的一部分,而不是将其放入asp.net core api中呢。并介绍了一些使用方法。最简单的方法是将Microsoft.Extensions.DependencyInjection与AddHttpClient
扩展方法一起使用
static void Main(string[] args)
{
var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
var client = httpClientFactory.CreateClient();
}
static void Main(字符串[]args)
{
var serviceProvider=new servicecolection().AddHttpClient().BuildServiceProvider();
var httpClientFactory=serviceProvider.GetService();
var client=httpClientFactory.CreateClient();
}
感谢您的回复
所以可以在控制台应用程序中使用
有几种方法可以做到这一点,这取决于你想走哪条路。
这里有两个:
请参见此处,了解在接受的答案中仅提供第一种建议方法的示例代码:
services.AddHttpClient<IFoo, Foo>(); // where services is of type IServiceCollection
其中一个答案表明 您不需要ASP.NET来使用它 但是,您需要一点工作才能将其纳入依赖注入(DI):
- 安装microsoft.extensions.http(与ASP.NET无关)
- 配置DI时,请使用此扩展。它注册builders/httpclientFactory/。。。(在github上查看其源代码)
- 如果希望使用不同的名称/设置注册HttpClient,以便与不同的web服务器通信(不同的设置,例如:不同的基本URL)
- 如果您想添加delegatehendler,您需要将其同时添加到httpClient和DI容器中
ServiceCollection .AddHttpClient(clientName, x => x.BaseAddress = new Uri("http://www.google.com")) .AddHttpMessageHandler<DummyDelegateHandler>(); ServiceCollection.AddScoped<DummyDelegateHandler>();
servicecolection .AddHttpClient(clientName,x=>x.BaseAddress=新Uri(“http://www.google.com")) .AddHttpMessageHandler(); ServiceCollection.addScope();
- 注册您的HttpClient以使用HttpClientFactory
ServiceCollection.AddScoped<HttpClient>(x => x.GetService<IHttpClientFactory>().CreateClient("yourClientName"));
ServiceCollection.addScope(x=> x、 GetService().CreateClient(“yourClientName”);
- 要解析http客户端,请执行以下操作:
var client = ServiceProvider.GetService<HttpClient>();
var client=ServiceProvider.GetService();
ServiceCollection.AddScoped<HttpClient>(x =>
x.GetService<IHttpClientFactory>().CreateClient("yourClientName"));
var client = ServiceProvider.GetService<HttpClient>();