简体   繁体   English

如何从 HttpClient 帮助程序 class 读取配置数据

[英]How to read Configuration data from a HttpClient helper class

In my Blazor Server Application, I'm trying to read configuration data from appsettings.json from within a helper class that is used for configuring an HttpClient service to call a web API. In my Blazor Server Application, I'm trying to read configuration data from appsettings.json from within a helper class that is used for configuring an HttpClient service to call a web API. In my Program.cs file, I'm adding the HttpClient service as:在我的Program.cs文件中,我将HttpClient服务添加为:

builder.Services.AddHttpClient<MyHelper>();

I need to access the App configuration inside my Helper class, which is as follows:我需要访问我的 Helper class 里面的 App 配置,如下:

public class MyHelper
{
    private readonly HttpClient _httpClient;

    public MyHelper(HttpClient httpClient)
    {
        _httpClient = httpClient;    
       
        _httpClient.DefaultRequestHeaders.Add(
            HeaderNames.ContentType, "application/json");

        //Read configuration from appsettings.json

        );    
    }
}

Thank you.谢谢你。

You may inject IConfiguration to access the appsettings.json contents.您可以注入IConfiguration以访问appsettings.json内容。

public class MyHelper
{
    private readonly HttpClient _httpClient;

    public MyHelper(HttpClient httpClient,IConfiguration configuration)
    {
        _httpClient = httpClient;

       
        _httpClient.DefaultRequestHeaders.Add(HeaderNames.ContentType, "application/json");

        //Read configuration from appsettings.json
        
        var connection=  configuration["connectionString"];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM