余晖落尽暮晚霞,黄昏迟暮远山寻
本站
当前位置:网站首页 > 编程知识 > 正文

HttpClient使用(httpclient使用教程)

xiyangw 2022-11-24 16:39 27 浏览 0 评论

起因

在项目中需要访问Http请求的时候,通常都是使用WebRequest,主要是老项目(你懂得).如果不是老项目,应该使用HttpClient,但在.Net Core 2.1之后,官方可推荐使用使用HttpClientFactory.

1. HttpClient的使用

public static async void UseHttp()
{
    //在项目中HttpClient要静态单实例
    //这里只是为了方便
    HttpClient httpClient = new HttpClient(); 
    httpClient.BaseAddress = new Uri("http://localhost:5000"); //要访问的基地址,ip加端口

    string result = await httpClient.GetStringAsync("/Home/GetHtmlData");
    Console.WriteLine(result);
}

2.在Asp.Net Core使用HttpClientFactory

在Startup文件的ConfigureServices函数,注册HttpClient中间件

//1.在容器中注册HttpClient中间件
services.AddHttpClient("baidu", client =>
{
    client.BaseAddress = new Uri("http://localhost:5000");  
    //还可以请求定制化
});
/// <summary>
/// 在控制器中的构造函数注入IHttpClientFactory
/// </summary>
/// <param name="logger">日志</param>
/// <param name="cache">缓存</param>
/// <param name="httpClientFactory">容器在实例化HomeController的时候,会先实现IHttpClientFactory的实现DefaultHttpClientFactory(AddHttpClient在容器中注册)</param>
public HomeController(ILogger<HomeController> logger,
                        IMemoryCache cache,
                        IHttpClientFactory httpClientFactory)
{
    Console.WriteLine("有参数构造 HomeController");
    this._logger = logger;
    this._httpClientFactory = httpClientFactory;
}
/// <summary>
/// 在Action中使用HttpClient请求
/// </summary>
/// <returns></returns>
public async Task<string> GetHtmlData()
{
    //通过DefaultHttpClientFactory的CreateClient获取HttpClient实例
    var client = _httpClientFactory.CreateClient("baidu");
    return await client.GetStringAsync("/");
}

在Asp.Net Core的HttpClient中间件源码

Asp.Net Core 5源码(2022.03.15,刚刚对比最新的代码,好像变化不大):


public static IServiceCollection AddHttpClient(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    services.AddLogging();
    services.AddOptions();

    //
    // 向容器添加DefaultHttpClientFactory实例
    //
    services.TryAddTransient<HttpMessageHandlerBuilder, DefaultHttpMessageHandlerBuilder>();
    services.TryAddSingleton<DefaultHttpClientFactory>();
    services.TryAddSingleton<IHttpClientFactory>(serviceProvider => serviceProvider.GetRequiredService<DefaultHttpClientFactory>());
    services.TryAddSingleton<IHttpMessageHandlerFactory>(serviceProvider => serviceProvider.GetRequiredService<DefaultHttpClientFactory>());

    //
    // Typed Clients
    //
    services.TryAdd(ServiceDescriptor.Transient(typeof(ITypedHttpClientFactory<>), typeof(DefaultTypedHttpClientFactory<>)));
    services.TryAdd(ServiceDescriptor.Singleton(typeof(DefaultTypedHttpClientFactory<>.Cache), typeof(DefaultTypedHttpClientFactory<>.Cache)));

    //
    // Misc infrastructure
    //
    services.TryAddEnumerable(ServiceDescriptor.Singleton<IHttpMessageHandlerBuilderFilter, LoggingHttpMessageHandlerBuilderFilter>());

    // This is used to track state and report errors **DURING** service registration. This has to be an instance
    // because we access it by reaching into the service collection.
    services.TryAddSingleton(new HttpClientMappingRegistry());

    // Register default client as HttpClient
    services.TryAddTransient(s =>
    {
        return s.GetRequiredService<IHttpClientFactory>().CreateClient(string.Empty);
    });

    return services;
}

public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    if (name == null)
    {
        throw new ArgumentNullException(nameof(name));
    }

    AddHttpClient(services);

    return new DefaultHttpClientBuilder(services, name);
}

public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name, Action<HttpClient> configureClient)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    if (name == null)
    {
        throw new ArgumentNullException(nameof(name));
    }

    if (configureClient == null)
    {
        throw new ArgumentNullException(nameof(configureClient));
    }

    AddHttpClient(services);

    var builder = new DefaultHttpClientBuilder(services, name);
    builder.ConfigureHttpClient(configureClient);
    return builder;
}

public static IServiceCollection AddHttpClient(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    services.AddLogging();
    services.AddOptions();

    //
    // Core abstractions
    //
    services.TryAddTransient<HttpMessageHandlerBuilder, DefaultHttpMessageHandlerBuilder>();
    services.TryAddSingleton<DefaultHttpClientFactory>();
    services.TryAddSingleton<IHttpClientFactory>(serviceProvider => serviceProvider.GetRequiredService<DefaultHttpClientFactory>());
    services.TryAddSingleton<IHttpMessageHandlerFactory>(serviceProvider => serviceProvider.GetRequiredService<DefaultHttpClientFactory>());

    //
    // Typed Clients
    //
    services.TryAdd(ServiceDescriptor.Transient(typeof(ITypedHttpClientFactory<>), typeof(DefaultTypedHttpClientFactory<>)));
    services.TryAdd(ServiceDescriptor.Singleton(typeof(DefaultTypedHttpClientFactory<>.Cache), typeof(DefaultTypedHttpClientFactory<>.Cache)));

    //
    // Misc infrastructure
    //
    services.TryAddEnumerable(ServiceDescriptor.Singleton<IHttpMessageHandlerBuilderFilter, LoggingHttpMessageHandlerBuilderFilter>());

    // This is used to track state and report errors **DURING** service registration. This has to be an instance
    // because we access it by reaching into the service collection.
    services.TryAddSingleton(new HttpClientMappingRegistry());

    // Register default client as HttpClient
    services.TryAddTransient(s =>
    {
        return s.GetRequiredService<IHttpClientFactory>().CreateClient(string.Empty);
    });

    return services;
}

public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    if (name == null)
    {
        throw new ArgumentNullException(nameof(name));
    }

    AddHttpClient(services);

    return new DefaultHttpClientBuilder(services, name);
}

public static IHttpClientBuilder AddHttpClient(this IServiceCollection services, string name, Action<HttpClient> configureClient)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    if (name == null)
    {
        throw new ArgumentNullException(nameof(name));
    }

    if (configureClient == null)
    {
        throw new ArgumentNullException(nameof(configureClient));
    }

    AddHttpClient(services);

    var builder = new DefaultHttpClientBuilder(services, name);
    builder.ConfigureHttpClient(configureClient);
    return builder;
}

在Asp.Net Core 6加入Minimal API

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
//在Asp.Net 6中,使用Minimal api
builder.Services.AddHttpClient("test", client =>
{
    client.BaseAddress = new Uri("http://localhost:5000");
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

//在这里注入IHttpClientFactory
app.MapGet("/", async (IHttpClientFactory httpClientFactory) =>
{
    var client = httpClientFactory.CreateClient("test");
    return await client.GetStringAsync("/");
});

app.Run();

在Asp.Net Core 6中使用Minimal API简化项目

个人能力有限,如果您发现有什么不对,请私信我

如果您觉得对您有用的话,可以点个赞或者加个关注,欢迎大家一起进行技术交流

相关推荐

学 Web 前端开发,培训还是自学靠谱?(想学web前端,哪家培训机构好)
学 Web 前端开发,培训还是自学靠谱?(想学web前端,哪家培训机构好)

对于学Web前端开发,培训还是自学靠谱这个问题,千锋广州小编认为得从几个方面去考虑:一、自己的对专业及自身学习能力、毅力的定位1.自学需要明确的学习目标、精...

2023-03-21 18:52 xiyangw

成都自学前端需要多长时间(成都web前端培训学校哪个好)
成都自学前端需要多长时间(成都web前端培训学校哪个好)

  Web前端发展前景好,薪资待遇高,是现在很多IT从业人员看好的岗位。那么自学Web前端难不难呢?需要多长时间呢?知了堂Web前端培训机构小编为您详细介绍一下...

2023-03-21 18:52 xiyangw

怎么才能四个月把web前端学好学深入并找到工作?

一入前端深似海,从此工作找不来。笑话了笑话,但是现在前端邻域的确是新人初级很多,但是绝大部分前端职位都要求技术过硬甚至有工作经验,这让应届生,转行新人怎么办呢?其实还是有办法的,那就是把前端技术学好学...

常州web前端培训,转行想学,学前端要多久?(web前端培训班有哪些)

web前端开发主要是指将APP软件前端、网页界面设计、后端技术开发程序相链接,是之顺利完成交互响应的操作的岗位。学习web前端不需要多么深厚的编程代码技术,所以学习起来会简单许多。那么学web前端多久...

新手学习web前端要学多久?(web前端需要学多久)
新手学习web前端要学多久?(web前端需要学多久)

新手学习web前端要学多久,怎么开始学习才能更好的掌握web前端技术的内容,能够达到企业的就业要求。对于想学习web前端的同学来说,想要学好web前端技术需要学...

2023-03-21 18:51 xiyangw

武汉Web前端开发培训班费用大概需要多少呢?(web前端开发技术培训)
武汉Web前端开发培训班费用大概需要多少呢?(web前端开发技术培训)

前端工程师的高薪成为很多人加入这个行业的源动力,据了解目前前端工程师的年薪待遇平均在10万以上,高级Web前端工程师年薪达30—50万,很多企业对于与Web前端...

2023-03-21 18:51 xiyangw

小白自学前端三个月(小白学前端一般学多久)

我自学前端快三个月了,基本上都是早上七点半左右开始学一直到晚上十一二点,我目前只学了html、css、javascript、以及vue.js,刚开始的时候学的还蛮轻松的,当学到js后半段的时候就有点开...

三个月速成班能成为程序员吗?(三个月速成班都有什么)
三个月速成班能成为程序员吗?(三个月速成班都有什么)

我们上大学的时候有“程序员”这个课程吗?当然没有。那大学的时候有程序员这个专业吗?就是大学期间就专门学一个程序的那种?我知道有计算机专业,有软件专业,但是有程...

2023-03-21 18:50 xiyangw

前端要学多久?要掌握哪些技术才能就业?(前端需要学到什么程度)
前端要学多久?要掌握哪些技术才能就业?(前端需要学到什么程度)

前端要学多久?要掌握哪些技术才能就业?这是准备踏入前端学习,或者是刚入门的小伙伴都比较关心的问题。关于学什么,我们很容易从培训机构或者是网上获得前端的学习知识路...

2023-03-21 18:50 xiyangw

大一学习软件开发需要多久能入门(大学大一软件工程主要学什么)
大一学习软件开发需要多久能入门(大学大一软件工程主要学什么)

首先,对于大一的同学来说,学习软件开发技术是不错的选择,未来更多专业的学生都需要具备一定的软件开发知识,这一点在工业互联网时代会有更加明显的体现,掌握一定的软件...

2023-03-21 18:50 xiyangw

Web前端:成为Web开发人员需要多长时间?(web前端开发多少钱)
Web前端:成为Web开发人员需要多长时间?(web前端开发多少钱)

  由于网站是目前每个小型到大型组织的需求,因此对Web开发人员的需求非常高。预计这种需求在未来会进一步增长,这就是为什么许多学生认为Web开发是他们职业生涯的...

2023-03-21 18:50 xiyangw

学Web前端好找工作吗 一般需要用多少时间(学web前端可以做什么工作)
学Web前端好找工作吗 一般需要用多少时间(学web前端可以做什么工作)

  学Web前端好找工作吗?一般需要用多少时间?在编程领域,与用户接触最多的是前端,华丽的效果、引人注目的动效都是前端工作人员工作的重要内容。目前各大企业对于W...

2023-03-21 18:49 xiyangw

在尚学堂学习前端的三个月,我学会了….(尚学堂前端培训视频百度网盘)

在尚学堂的培训就要结束了,在这简短而充实的3个月中,有迷茫,有失落,有努力,有纠结,可是最多的,还是收获。这三个月的学习从前端开发的基础开始,学习使用HTML,CSS,JavaScript等一系列前...

怎样学前端?前端的培训机构(怎么学好前端)

首先告诉你的是,零基础学习开始学习web前端肯定难,web前端的专业程度本身就不简单,学习这事本来就是一件非常煎熬的事情,人都不愿意学习,可是没办法,为了生存掌握一个技能,如果你认真的对待,你就找不到...

学习web前端培训大概要花多少费用?(web前端培训哪里)
学习web前端培训大概要花多少费用?(web前端培训哪里)

学习web前端开发是目前非常热门的一个领域,它涉及到各种不同的技术和工具,包括HTML、CSS、JavaScript、前端框架和库、版本控制等等。如果你对...

2023-03-21 18:49 xiyangw

取消回复欢迎 发表评论: