如何注入 httprequestmessage /端点

how to inject a httprequestmessage / endpoint

我的 REST API 中有一个控制器,我在其中执行 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();
}

事实是,通过接口注入 api 端点显然更好,老实说,我不知道那是什么或如何完成的。

我确实注入了 HttpClient 和 IConfiguration,但我已经做过好几次并看到其他人这样做了。但只是注入一个端点(没有 IConfiguration),对我来说似乎很陌生。那个...只是因为我去掉了对问题没有影响的代码。

是否有任何简单的方法来注入端点 - 只有我不明白其中的原因吗?

我想我必须创建一个接口,并在其中一些逻辑只是 returns 端点?但这不就是双重工作吗?

我的解决方案:

目前我能想到的唯一解决方法就是注入一个字符串:

private readonly string _myEndpoint;

然后注入:

_myEndpoint = Environment.GetEnvironmentVariable("MY_ENDPOINT");

最后在我的 httpRequestMessage 中使用它:

var httpRequest = new HttpRequestMessage(HttpMethod.Get, _myEndpoint);

这不是一个接口,但我还是不使用 IConfiguration 接口,也没有写很多不需要的代码。

如果有更好/更聪明的建议,请大声说出来。

有一种方法可以通过以下方式将 "options" 加载到服务集合中:

services.Configure<EndpointConfig>(Configuration.GetSection("EndPointConfig"));

此处的 EndpointConfig 是您必须定义的 class:

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

在此特定示例中,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;
}

如果您想尝试一下,这里有一些很好的文档:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1


如果您不想在 appsettings.json 中定义一个 EndpointConfig 部分,就像您在评论中描述的那样,那么您只需使用配置对象配置 i:

services.Configure<EndpointConfig>(Configuration);

现在它将在您的应用程序设置 json:

的基础对象中搜索 属性 名称(在本例中为 EndpointUrl
{
   "EndpointUrl" : "https://localhost"
}

如果您想寻找一个不同的名称,即 My_Endpoint,您只需重命名您的 属性:

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