如何为 Azure Function v2 正确导入 Nuget 包?

How do I import a Nuget package correctly for Azure Function v2?

我使用 Azure 函数核心工具来创建我的函数。我正在尝试导入 Newtonsoft.Json,但无法使其正常工作。这是我的基本设置:

function.proj:

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>  
<ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="11.0.2"/>
</ItemGroup>

function.json:

{
  "disabled": false,
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 * * * * *"
    }
  ]
}

run.csx:

using System;
using Newtonsoft.Json;

public static void Run(TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}

host.json:

{
   "version":  "2.0"
}

当我运行"func host start"时,一碰到"using Newtonsoft.Json"就崩溃了。

它似乎在正确监控我的 function.proj 文件,因为每次我保存它时,它都声称它正在恢复我的包。

我是不是做错了什么?我怎样才能得到我的 Nuget 包?

为了在 .csx 文件中引用外部依赖项,您需要在文件顶部添加 #r <PackageName>(本例中为 #r Newtonsoft.Json)。

只有某些依赖项会在 Azure Functions 中自动引用,select 其他依赖项无需将它们添加到您的 project.json 或 function.proj 文件中即可使用,只要您使用#r 符号。如需更完整的列表,请查看 Azure Functions 的 C# developer reference