在 .netcore 中向 HttpClient 添加标头参数

问题描述 投票:0回答:1

我有这个类在我的应用程序中注册 httpClient 和所有依赖项。

public static class InternalAdminServiceRegister
{
    public const string DefaultConfigSectionName = "InternalApisOptions:Admin";

    public static IServiceCollection AddAdminInternalServices(
        this IServiceCollection services,
        IConfiguration configuration,
        string configSectionName = DefaultConfigSectionName)
    {
        services.Configure<AdminOptions>(configuration.GetSection(configSectionName));
        services.AddHttpClient<IInternalAdminService, InternalAdminService>((sp, client) =>
        {
            var options = sp.GetRequiredService<IOptions<AdminOptions>>().Value;
            client.BaseAddress = new Uri(options.ServiceUrl);
            client.Timeout = TimeSpan.FromMilliseconds(options.TimeoutMs);
        }).AddPolicyHandler(GetCircuitBreakerPolicy());
        return services;
    }

    private static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy()
        => HttpPolicyExtensions
            .HandleTransientHttpError()
            .CircuitBreakerAsync(handledEventsAllowedBeforeBreaking: 5, durationOfBreak: TimeSpan.FromSeconds(7));

}

如您所见,我班上有一个 httpclient。我想从

program.cs

传递一个标头参数
var builder = MtsHost.CreateWebApplication(args);
builder.Services.AddAdminInternalServices(builder.Configuration);

我认为最好的解决方案是在构造函数中使用 AddHttpMessageHandler 作为参数。但我不知道如何使用它

我的解决方案,但我认为这不是最好的解决方案

public static class InternalAdminServiceRegister
{
    public const string DefaultConfigSectionName = "InternalApisOptions:Admin";

    public static IServiceCollection AddAdminInternalServices(
        this IServiceCollection services,
        IConfiguration configuration,
        string configSectionName = DefaultConfigSectionName,string endpointService="")
    {
        services.Configure<AdminOptions>(configuration.GetSection(configSectionName));
        services.AddHttpClient<IInternalAdminService, InternalAdminService>((sp, client) =>
        {
            var options = sp.GetRequiredService<IOptions<AdminOptions>>().Value;
            client.BaseAddress = new Uri(options.ServiceUrl);
            client.Timeout = TimeSpan.FromMilliseconds(options.TimeoutMs);
            if(!string.IsNullOrEmpty(endpointService)) client.DefaultRequestHeaders.Add(endpointService, "true") ;
        }).AddPolicyHandler(GetCircuitBreakerPolicy());
     
        return services;
    }

    private static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy()
        => HttpPolicyExtensions
            .HandleTransientHttpError()
            .CircuitBreakerAsync(handledEventsAllowedBeforeBreaking: 5, durationOfBreak: TimeSpan.FromSeconds(7));

}
asp.net-core .net-core httpclient
1个回答
0
投票

对于添加标题,以下方法有效。

var request = new HttpRequestMessage(HttpMethod.Get,"https://localhost:7171/identity");
        request.Headers.Add("header1", "value1");    //add headers
        request.Headers.Add("header2", "value2");

        var response = await _client.SendAsync(request);
        if (response.IsSuccessStatusCode)
        {
            content = await response.Content.ReadAsStringAsync();
        }

使用客户端需要在program.cs中注册服务

builder.Services.AddHttpClient();

并在你的类中注入Httpclient来使用

public class InternalAdminServiceRegister
    {
        private readonly HttpClient _client;

        public InternalAdminServiceRegister(HttpClient httpClient)
        {
            this._client = httpClient;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.