'IServiceCollection' 不包含 'AddApiVersioning' 对 webapi vs 代码项目使用 dot net 5 的定义

'IServiceCollection' does not contain a definition for 'AddApiVersioning' using dot net 5 for a webapi vs code project

我正在尝试将版本控制 (Microsoft.AspNet.WebApi.Versioning) 与 dotnet 5 一起用于 webapi 项目。我已经添加了 nuget 包,但出现以下错误:

'IServiceCollection' 不包含 'AddApiVersioning' 的定义并且没有可访问的扩展方法 'AddApiVersioning' 接受类型为 [=34 的第一个参数=] 可以找到(您是否缺少 using 指令或程序集引用?)

这一行:

services.AddApiVersioning();

在我的 Startup.cs

我的 .csproj 文件如下所示:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Identity.Web" Version="1.0.0"/>
    <PackageReference Include="Microsoft.Identity.Web.UI" Version="1.0.0"/>
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3"/>
    <PackageReference Include="Microsoft.Data.SqlClient" Version="2.0.1"/>
    <PackageReference Include="Dapper" Version="2.0.35"/>
    <PackageReference Include="Azure.Storage.Blobs" Version="12.4.1"/>
    <PackageReference Include="Microsoft.AspNet.WebApi.Versioning" Version="4.1.1"/>
  </ItemGroup>
</Project>

我尝试遵循一些示例,例如 this one and this one and this one,我应该有以下 'using directive',我有:

using Microsoft.AspNetCore.Mvc;

有人遇到同样的挑战吗? .net 5 是否支持版本控制?

您正在使用包 Microsoft.AspNet.WebApi.Versioning,它是 ASP.NET Web API 的 API 版本控制包,是 .NET 的经典 Web API 框架框架。

您正在使用 ASP.NET 核心,因此您需要 Microsoft.AspNetCore.Mvc.Versioning 软件包。这个包也是您链接的教程中提到的包。

但是很容易混淆这些包,因为它们都来自 same repository on GitHub,后者还为特殊用例生成了一些额外的包。

对于 .net6,我从 nuget 手动添加

Microsoft.AspNetCore.Mvc.Versioning

并添加到 Program.cs

using Microsoft.AspNetCore.Mvc;

效果很好。 visual studio 2022 与 .net6 组合有这样的问题。这个问题我遇到过好几次了。