繁体   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. 在我的Program.cs文件中,我将HttpClient服务添加为:

builder.Services.AddHttpClient<MyHelper>();

我需要访问我的 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

        );    
    }
}

谢谢你。

您可以注入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