gpt4 book ai didi

c# - 为什么 HttpClient 不保存基地址,即使它在 Startup 中设置

转载 作者:行者123 更新时间:2023-12-04 00:51:47 26 4
gpt4 key购买 nike

在我的 .net core web api 项目中,我想点击一个外部 API,以便我得到预期的响应。
我注册和使用 HttpClient 的方式如下。在启动时,我添加了以下称为命名类型化 httpclient 方式的代码。

 services.AddHttpClient<IRecipeService, RecipeService>(c => {
c.BaseAddress = new Uri("https://sooome-api-endpoint.com");
c.DefaultRequestHeaders.Add("x-raay-key", "123567890754545645gggg");
c.DefaultRequestHeaders.Add("x-raay-host", "sooome-api-endpoint.com");
});
除此之外,我还有 1 个服务可以在其中注入(inject) HttpClient。

public class RecipeService : IRecipeService
{
private readonly HttpClient _httpClient;

public RecipeService(HttpClient httpClient)
{
_httpClient = httpClient;
}

public async Task<List<Core.Dtos.Recipes>> GetReBasedOnIngAsync(string endpoint)
{

using (var response = await _httpClient.GetAsync(recipeEndpoint))
{
// ...
}
}
}

创建 httpClient 时,如果我将鼠标悬停在对象本身上,则缺少基本 URI/Headers,我不明白为什么会发生这种情况。如果有人可以显示一些光,我将不胜感激:)
更新第一
该服务正在以下所示的 Controller 之一中使用。服务由 DI 注入(inject),然后将相对路径解析为服务(我假设我已经将基本 URL 存储在客户端中)也许我做错了?

namespace ABC.Controllers
{
[ApiController]
[Route("[controller]")]
public class FridgeIngredientController : ControllerBase
{
private readonly IRecipeService _recipeService;
private readonly IMapper _mapper;

public FridgeIngredientController(IRecipeService recipeService, IMapper mapper)
{
_recipeService = recipeService;
_mapper = mapper;
}

[HttpPost("myingredients")]
public async Task<ActionResult> PostIngredients(IngredientsDto ingredientsDto)
{
var readyUrIngredientStr = string.Join("%2", ingredientsDto.ingredients);

var urlEndpoint = $"recipes/findByIngredients?ingredients={readyUrIngredientStr}";
var recipesResponse = await _recipeService.GetRecipeBasedOnIngredientsAsync(urlEndpoint);
InMyFridgeRecipesDto recipesFoundList = new InMyFridgeRecipesDto
{
FoundRecipes = recipesResponse
};

return Ok(recipesFoundList);
}
}
}


有什么建议么?

最佳答案

发生这种情况的一个简单而令人沮丧的原因是您的服务集合分配的顺序。
分配依赖服务之后 HTTPClient 不起作用,它必须在之前:

// NOT WORKING - BaseAddress is null
services.AddTransient<Controller1>();
services.AddTransient<Controller2>();

services.AddHttpClient<HttpService>(client =>
{
client.BaseAddress = new Uri(baseAdress);
});

services.AddTransient<HttpService>();


// WORKING - BaseAddress is not null
services.AddTransient<Controller1>();
services.AddTransient<Controller2>();
services.AddTransient<HttpService>();

services.AddHttpClient<HttpService>(client =>
{
client.BaseAddress = new Uri(baseAdress);
});

关于c# - 为什么 HttpClient 不保存基地址,即使它在 Startup 中设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65777953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com