gpt4 book ai didi

c# - IHttpClientFactory 的解析服务在 Azure 函数上失败

转载 作者:行者123 更新时间:2023-12-05 05:06:00 27 4
gpt4 key购买 nike

我正在尝试在 Azure Function v3 上注入(inject) IHttpClientFactory 服务,但我不断收到以下错误消息,提示解析服务失败。我使用 azure-functions-core-tools@v3 在本地运行 Azure Function。

[2/14/2020 5:45:19 PM] Executed 'Foo' (Failed, Id=24489b3b-af99-417e-b175-443b76c241d5)
[2/14/2020 5:45:19 PM] Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'System.Net.Http.IHttpClientFactory' while attempting to activate 'MyFunction.Function.Foo'.

我有一个启动类,应该为 IHttpClientFactory 注入(inject)服务。

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

namespace MyFunction
{
public class Startup : FunctionsStartup
{

public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient();
}
}
}

下面是一个 azure 函数类,它使用 IHttpClientFactory 的注入(inject)服务来创建 HTTP 客户端并向服务器发送 GET 请求。

using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace MyFunction.Function
{
public class Foo
{
private readonly HttpClient httpClient;
public Scrape(IHttpClientFactory httpClientFactory)
{
httpClient = httpClientFactory.CreateClient();
}

[FunctionName("Foo")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
var result = await httpClient.GetAsync("https://google.com");
var data = await result.Content.ReadAsStringAsync();
return new OkObjectResult(data);
}
}
}

我错过了什么吗?

最佳答案

看起来您的 startup.cs 类缺少它的程序集引用?

[assembly: FunctionsStartup(typeof(MyFunction.Startup))]

尝试将其添加到启动类中。在顶部的 using 语句之后和任何 namespace 声明之前添加它。

此外,我见过的大多数示例都显示了在函数执行期间实际创建的客户端,而不是在默认构造函数中创建的。

using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace MyFunction.Function
{
public class Foo
{
private readonly HttpClient httpClient;
public Scrape(IHttpClientFactory httpClientFactory)
{
factory = httpClientFactory;
}

[FunctionName("Foo")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
HttpClient httpClient = factory.CreateClient();
var result = await httpClient.GetAsync("https://google.com");
var data = await result.Content.ReadAsStringAsync();
return new OkObjectResult(data);
}
}
}

关于c# - IHttpClientFactory 的解析服务在 Azure 函数上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60231366/

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