Azure Function加载System.Net.Http 7.0.0.0失败问题求助
解决Azure Function启动时System.Net.Http版本加载错误
核心修复方案
1. 配置绑定重定向
在项目的local.settings.json或生成的FunctionName.dll.config中添加绑定重定向,让运行时自动适配可用版本:
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="你项目实际引用的版本,比如4.2.0.0或当前框架自带版本" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
如果是.NET 6+的Azure Function,也可以直接在.csproj中添加配置,让编译器自动生成绑定重定向:
<PropertyGroup> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType> </PropertyGroup>
2. 调整项目依赖版本
- 打开NuGet包管理器,检查是否手动引用了
System.Net.Http包,若有则降级到与Azure Function Runtime兼容的版本(比如.NET 6 Function可使用4.3.4版本) - 确保项目目标框架版本与Azure Runtime匹配,避免引用过高版本的NuGet包
3. 改用依赖注入管理HttpClient
Azure Function推荐通过依赖注入获取HttpClient,既能避免版本冲突,也符合最佳实践:
首先在Startup.cs中注册HttpClient:
using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Hosting; using Microsoft.Extensions.DependencyInjection; namespace Tesi.Worker { public class Startup : IWebJobsStartup { public void Configure(IWebJobsBuilder builder) { builder.Services.AddHttpClient(); } } }
然后修改函数类注入并使用HttpClient:
using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using System; using System.Net.Http; using System.Threading.Tasks; namespace Tesi.Worker { public class StandingsFunctions { private readonly HttpClient _client; public StandingsFunctions(HttpClient client) { _client = client; } [FunctionName("WeeklyUpdateStandings")] public async Task Run([TimerTrigger("0 */1 * * * *")] TimerInfo myTimer, ILogger log) { log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}"); HttpContent content = null; var response = await _client.PostAsync("https://sportdataapi.azurewebsites.net/api/WebHook/UpdateStandings", content); if (response.IsSuccessStatusCode) { log.LogInformation("Post 请求成功 " + response.StatusCode.ToString()); } else { log.LogInformation("请求出错!"); } } } }
疑问解答
1. 框架自带的System.Net.Http目录位置
- .NET Framework:默认位于
C:\Windows\Microsoft.NET\Framework\[版本号]\System.Net.Http.dll(比如Framework 4.8对应C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Net.Http.dll) - .NET Core/.NET 5+:作为共享框架一部分,位于
C:\Program Files\dotnet\shared\Microsoft.NETCore.App\[版本号]\System.Net.Http.dll
2. 如何降低版本测试
- 打开NuGet包管理器,找到
System.Net.Http包,选择较低版本(如4.3.4)安装 - 若未手动引用过该包,先搜索并安装指定版本,覆盖框架默认引用
- 重新编译并启动Function,观察错误是否消失
3. 能否删除完整框架自行安装所有包
- .NET Framework:不行,核心功能依赖系统安装的完整框架,无法完全替换
- .NET Core/.NET 5+:可以使用独立部署模式,将所有依赖(包括框架)打包到部署文件中,无需目标机器安装.NET运行时。在
.csproj中添加如下配置:
<PropertyGroup> <PublishSingleFile>true</PublishSingleFile> <SelfContained>true</SelfContained> <RuntimeIdentifier>win-x64</RuntimeIdentifier> <!-- 根据目标平台选择,如linux-x64 --> </PropertyGroup>
执行dotnet publish命令生成独立部署包即可。
内容的提问来源于stack exchange,提问作者Matteo Pagliarello
相关产品推荐
相关产品推荐

