C# 如何注入httprequestmessage/endpoint

C# 如何注入httprequestmessage/endpoint,c#,api,dependency-injection,controller,httprequest,C#,Api,Dependency Injection,Controller,Httprequest,我在restapi中有一个控制器,我在其中执行HttpRequestMessage。我现在的做法是使用IConfiguration接口获取端点作为变量: public class MyController : Controller { private readonly IConfiguration _configuration; private readonly HttpClient _httpClient; public MyController(IConfiguration configur

我在restapi中有一个控制器,我在其中执行HttpRequestMessage。我现在的做法是使用IConfiguration接口获取端点作为变量:

public class MyController : Controller
{
private readonly IConfiguration _configuration;
private readonly HttpClient _httpClient;
public MyController(IConfiguration configuration, HttpClient httpClient){
_configuration = configuration;
_httpClient = httpClient;
}
...
...
[HttpGet]
public async Task<IActionResult> Get(){
...
...
var httpRequest = new HttpRequestMessage(HttpMethod.Get, _configuration["MY_ENDPOINT"]);
await _httpClient.SendAsync(httpRequest);
...
...
return Ok();
}
然后注入它:

_myEndpoint = Environment.GetEnvironmentVariable("MY_ENDPOINT");
最后在我的httpRequestMessage中使用:

var httpRequest = new HttpRequestMessage(HttpMethod.Get, _myEndpoint);
这不是一个接口,但我不使用IConfiguration接口,也不编写很多不需要的代码


如果有更好/更聪明的建议,请大声呼喊。

有一种方法可以通过以下方式将“选项”加载到服务集合中:

services.Configure<EndpointConfig>(Configuration.GetSection("EndPointConfig"));
在此特定示例中,
appsettings.json
“EndPointConfig”需要一个EndpointUrl,下面是一个粗略的示例:

{
    "EndPointConfig" : {
        "EndpointUrl" : "https://localhost"
    }

}
然后,当您到达控制器时,您会像这样传入配置:

private readonly EndpointConfig _configuration;
private readonly HttpClient _httpClient;

public MyController(IOptions<EndpointConfig> configuration, HttpClient httpClient){
    _configuration = configuration.Value;
    _httpClient = httpClient;
}
现在,它将在appsettings json的基本对象中搜索属性名称(在本例中为
EndpointUrl
):

{
   "EndpointUrl" : "https://localhost"
}
如果要查找其他名称,即
My_Endpoint
,您只需重命名您的属性即可:

public class EndpointConfig 
{
    public string My_Endpoint {get; set;}
}

这似乎很像我想走的路。唯一的问题是,我的_端点已经是一个已知的变量,这就是我必须使用的变量。我是否仍然可以使用这种方法,但可以到达我的_端点?因为将它加载到服务集合中并创建一个单独的配置类正是我所要搜索的,但是如何创建一个从appsettings.json获取对象的类,这已经存在了,我不知道。我是否可以获取已经创建的MY_端点并使用您的设置来代替appsettings.json的endpointconfig?MY_端点是在哪里定义的?如果它在appsettings中,那么是的,您只需执行
services.Configure(配置)
并且它将在appsettings中搜索
EndpointUrl
(取自我的示例),如果您希望EndpointUrl是其他内容,您只需重命名appsettings.json中定义的classit上的属性,看起来像这样{“my_ENDPOINT”:“my_ENDPOINT2”:“my_ENDPOINT3”:“}我只对获取我的_端点感兴趣。按照您的设置方式—EndPointConfig有一个名为EndPointUrl的字符串,我可以看到我会将该字符串称为My_endpoint—但是当appsettings.json中My_endpoint上方没有对象时,它不会搜索不存在的“EndPointConfig”吗?很抱歉,没有清楚地理解这一部分。这取决于您在DI中如何配置它,在我的回答中,我描述了有一个
EndpointConfig
部分,但是如果您不想有该部分,您可以简单地执行
服务。配置(配置)EndpointConfig
部分:)
services.Configure<EndpointConfig>(Configuration);
{
   "EndpointUrl" : "https://localhost"
}
public class EndpointConfig 
{
    public string My_Endpoint {get; set;}
}