“IServiceCollection"不包含“AddControllers"的定义 [英] 'IServiceCollection' does not contain a definition for 'AddControllers'

查看:156
本文介绍了“IServiceCollection"不包含“AddControllers"的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ASP.NET Core 3.0 项目在以下启动时运行良好:

I have a ASP.NET Core 3.0 project running fine with the following startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();            
    services.AddControllers();
}

现在我想把这个设置移到另一个项目中,作为一个通用 dll,供许多其他 ASP.NET Core 3.0 项目使用,所有这些项目都将通过调用 services.Configure 来执行启动();,考虑到Configure是我自己创建的一个扩展方法.

Now I want to move this setup to another project, to serve as a Common dll to be used by dozens of other ASP.NET Core 3.0 projects where all of them will execute the startup with calling just services.Configure();, considering that Configure will be an extension method created by me.

为此,我使用以下 .csproj 文件创建了另一个项目:

For this, I've created another project with the following .csproj file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="2.2.0" />
  </ItemGroup>

</Project>

还有以下类:

using System;
using Microsoft.Extensions.DependencyInjection;

namespace MyCommon.Extensions
{
    public static class MyIServiceCollectionExtensions
    {
        public static class IServiceCollectionExtensions
        {
            public static IServiceCollection Configure(this IServiceCollection services)
            {
                services.AddCors();
                services.AddControllers();
                return services;
            }
        }
    }
}

这给了我以下构建错误:

This gives me the following build error:

IServiceCollection"不包含AddControllers"的定义

'IServiceCollection' does not contain a definition for 'AddControllers'

因为我已经添加了 Microsoft.AspNetCore.Mvc,我不明白为什么找不到AddControllers 方法.

As I've already added the Microsoft.AspNetCore.Mvc package, I don't understand why the AddControllers method couldn't be found.

推荐答案

我在 Asp .netcore 3.0 中得到了同样的结果.通过添加 Microsoft.AspNetCore.Mvc.NewtonsoftJson 包解决.

I got the same with Asp .netcore 3.0. Resolved it by adding Microsoft.AspNetCore.Mvc.NewtonsoftJson package.

这篇关于“IServiceCollection"不包含“AddControllers"的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆