没有为类型“Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory”注册服务。

75

我遇到了这个问题:No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered. 在ASP.NET Core 1.0中,当操作试图渲染页面时,似乎会出现此异常。

我进行了大量搜索,但没有找到解决方案,如果有人能帮我弄清楚发生了什么以及如何修复它,我将不胜感激。

我的代码如下:

我的project.json文件

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"

    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
    "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
    "EntityFramework.Commands": "7.0.0-rc1-final"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

我的Startup.cs文件

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OdeToFood.Services;

namespace OdeToFood
{
    public class Startup
    {
        public IConfiguration configuration { get; set; }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddScoped<IRestaurantData, InMemoryRestaurantData>();
            services.AddMvcCore();
            services.AddSingleton(provider => configuration);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //app.UseRuntimeInfoPage();

            app.UseFileServer();

            app.UseMvc(ConfigureRoutes);

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }

        private void ConfigureRoutes(IRouteBuilder routeBuilder)
        {
            routeBuilder.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}");
        }
    }
}

这发生在特定的页面上吗?您在该页面中试图做什么?还有,当您注释掉“IRestaurantData”的注册时,是否能够复制该问题? - Shyju
@Shyju,感谢您的回复。每当我尝试在homeController的任何操作中调用View()方法以显示视图时,它就会发生,即使我没有重载该方法,它仍然会抛出异常。即使我注释掉“IRestaurantData”注册服务,问题仍然存在,这个问题非常奇怪:(因为它似乎像是我缺少某些命名空间或其他东西,但是VS没有显示任何错误代码。 - Emmanuel Villegas
@Shyju 这是我正在使用的命名空间:using Microsoft.AspNetCore.Mvc; using OdeToFood.ViewModels; using OdeToFood.Services; using OdeToFood.Entities; - Emmanuel Villegas
14个回答

80
解决方案:Startup.cs中使用AddMvc()而不是AddMvcCore(),这样就能正常工作。
有关原因的详细信息,请参见此问题:

对于大多数用户来说,没有变化,您应该继续在启动代码中使用AddMvc()和UseMvc(...)。

对于真正勇敢的人,现在有一种配置体验,您可以从最小的MVC管道开始,然后添加功能以获得定制的框架。

https://github.com/aspnet/Mvc/issues/2872

您还可能需要在project.json中添加Microsoft.AspNetCore.Mvc.ViewFeature的引用。 https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.ViewFeatures/

66

如果你正在使用2.x版本,则在ConfigureServices中使用services.AddMvcCore().AddRazorViewEngine();

同时,如果你正在使用Authorize属性,请记得添加.AddAuthorization(),否则它将无法正常工作。

更新:对于3.1及以上版本,请使用services.AddControllersWithViews();


谢谢您的回答。对于我们的项目,是这个:services.AddControllersWithViews(); 非常感谢! - NFlows

31

我知道这是一篇旧文章,但当我将一个MVC项目迁移到.NET Core 3.0时,这是我在谷歌上的最佳搜索结果。将我的Startup.cs文件修改为以下内容后,问题得到了解决:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

13

在 .NET Core 3.1 中,我必须添加以下内容:

services.AddRazorPages();

ConfigureServices()

以下内容在Startup.csConfigure()

app.UseEndpoints(endpoints =>
{
     endpoints.MapRazorPages();
}

关键词是.NET Core 3.1,这两行代码立刻帮了我。 - moudrick

3
在2022年使用.NET 6.0时,
请将以下行添加到Program.cs文件中。
var builder = WebApplication.CreateBuilder(args); //After this line...
builder.Services.AddRazorPages(); //<--This line

2
解决方案:在Startup.cs中使用services.AddMvcCore(options => options.EnableEndpointRouting = false).AddRazorViewEngine();,它会起作用。
此代码已经针对asp.net core 3.1(MVC)进行了测试。

2

对于.NET Core 2.0,在ConfigureServices中使用:

services.AddNodeServices();

1

现在我遇到了同样的问题,我像你一样使用AddMvcCore。我发现错误信息已经很清楚地描述了问题,所以我假设在ConfigureServices函数中添加了AddControllersWithViews服务,这解决了我的问题。(我仍然使用AddMvcCore。)

    public void ConfigureServices(IServiceCollection services)
    {
        //...
        services.AddControllers();
        services.AddControllersWithViews();
        services.AddMvcCore();
        //...
    }    

1
对于Net Core(使用NET 6.0或更高版本和VS 2022),在尝试使用视图时可能会出现此错误。为了避免这个问题,在配置Program.cs时,请记得使用AddControllersWithViews而不是AddControllers。
修复的示例:
using Microsoft.EntityFrameworkCore;
using WebApp.Net.Core.Api.EF.Core.Angular.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var configurationService =  builder.Services.BuildServiceProvider().GetService<IConfiguration>();
builder.Services.AddDbContext<AppDbContext1>(options => options.UseSqlServer(configurationService.GetConnectionString("appSetttingsCon1")));
//builder.Services.AddControllers();//this will trigger the error when consuming views
builder.Services.AddControllersWithViews();//this fixes the issue

0
这个对我的情况有效:
services.AddMvcCore()
.AddApiExplorer();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接