简体   繁体   English

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

[英]No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered

I'm having this problem: No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered.我遇到了这个问题:没有注册“Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory”类型的服务。 In asp.net core 1.0, it seems that when the action try to render the view i have that exception.在 asp.net core 1.0 中,似乎当操作尝试呈现视图时,我有该异常。

I've searched a lot but I dont found a solution to this, if somebody can help me to figure out what's happening and how can I fix it, i will appreciate it.我已经搜索了很多,但我没有找到解决方案,如果有人可以帮助我弄清楚发生了什么以及如何解决它,我将不胜感激。

My code bellow:我的代码如下:

My project.json file我的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%" ]
  }
}

My Startup.cs file我的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?}");
        }
    }
}

Solution: Use AddMvc() instead of AddMvcCore() in Startup.cs and it will work.解决方案:Startup.cs使用AddMvc()而不是AddMvcCore()它将起作用。

Please see this issue for further information about why:请参阅此问题以获取有关原因的更多信息:

For most users there will be no change, and you should continue to use AddMvc() and UseMvc(...) in your startup code.对于大多数用户来说不会有任何变化,您应该继续在启动代码中使用 AddMvc() 和 UseMvc(...)。

For the truly brave, there's now a configuration experience where you can start with a minimal MVC pipeline and add features to get a customized framework.对于真正勇敢的人来说,现在有一种配置体验,您可以从最小的 MVC 管道开始,然后添加功能以获得自定义框架。

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

You might also have to add a reference to Microsoft.AspNetCore.Mvc.ViewFeature in project.json您可能还需要在project.json添加对Microsoft.AspNetCore.Mvc.ViewFeature的引用

https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.ViewFeatures/ https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.ViewFeatures/

If you're using 2.x then use services.AddMvcCore().AddRazorViewEngine();如果您使用的是2.x则使用services.AddMvcCore().AddRazorViewEngine(); in your ConfigureServices在您的ConfigureServices

Also remember to add .AddAuthorization() if you're using Authorize attribute, otherwise it won't work.如果您使用Authorize属性,还记得添加.AddAuthorization() ,否则它将不起作用。

Update: for 3.1 onwards use services.AddControllersWithViews();更新:从3.1开始使用services.AddControllersWithViews();

I know this is an old post but it was my top Google result when running into this after migrating an MVC project to .NET Core 3.0.我知道这是一篇旧帖子,但在将 MVC 项目迁移到 .NET Core 3.0 后遇到此问题时,这是我在 Google 上的最高结果。 Making my Startup.cs look like this fixed it for me:让我的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();
        });
    }
}

In .NET Core 3.1, I had to add the following:在 .NET Core 3.1 中,我必须添加以下内容:

services.AddRazorPages();

in ConfigureServices()ConfigureServices()

And the below in Configure() in Startup.cs下面是Startup.cs中的Configure()

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

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

services.AddNodeServices();

Solution: Use services.AddMvcCore(options => options.EnableEndpointRouting = false).AddRazorViewEngine();解决方案:使用services.AddMvcCore(options => options.EnableEndpointRouting = false).AddRazorViewEngine(); in Startup.cs and it will work.在 Startup.cs 中,它将起作用。

This code is tested for asp.net core 3.1 (MVC)此代码针对 asp.net core 3.1 (MVC) 进行了测试

Right now i has same problem, I was using AddMcvCore like you.现在我有同样的问题,我像你一样使用 AddMcvCore。 I found error self descriptive, as an assumption I added AddControllersWithViews service to ConfigureServices function and it fixed problem for me.我发现错误是自我描述性的,假设我将 AddControllersWithViews 服务添加到 ConfigureServices 函数,它为我解决了问题。 (I still use AddMvcCore as well.) (我仍然使用 AddMvcCore。)

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

Just add following code and it should work:只需添加以下代码,它应该可以工作:

   public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore()
                    .AddViews();

        }

For those that get this issue during .NetCore 1.X -> 2.0 upgrade, update both your Program.cs and Startup.cs对于在 .NetCore 1.X -> 2.0 升级期间遇到此问题的用户,请更新您的Program.csStartup.cs

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

public class Startup
{
// The appsettings.json settings that get passed in as Configuration depends on 
// project properties->Debug-->Enviroment Variables-->ASPNETCORE_ENVIRONMENT
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddTransient<IEmailSender, EmailSender>();

        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    // no change to this method leave yours how it is
    }
}

This one works for my case :这个适用于我的情况:

services.AddMvcCore()
.AddApiExplorer();

您在 startup.cs 中使用它

services.AddSingleton<PartialViewResultExecutor>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 单元测试模拟 ControllerContext HttpContext 没有为类型“Microsoft.AspNetCore.Mvc.View...ITempDataDictionaryFactory”注册服务 - Unit Tests Mock ControllerContext HttpContext No service for type 'Microsoft.AspNetCore.Mvc.View...ITempDataDictionaryFactory' has been registered 没有注册“Microsoft.AspNetCore.Mvc.ViewFeatures.PartialViewResultExecutor”类型的服务 - No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.PartialViewResultExecutor' has been registered 没有注册类型为“Microsoft.AspNetCore.Mvc ...”的服务 - No service for type 'Microsoft.AspNetCore.Mvc..." has been registered ASP.NET 核心 3:InvalidOperationException:没有 Microsoft.AspNetCore.Mvc.Routing.ControllerActionEndpointDataSource 类型的服务已注册 - ASP.NET Core 3: InvalidOperationException: No service for type Microsoft.AspNetCore.Mvc.Routing.ControllerActionEndpointDataSource has been registered 没有为“Microsoft.AspNetCore.Http.HttpContextAccessor”类型注册服务 - No service for type 'Microsoft.AspNetCore.Http.HttpContextAccessor' has been registered 没有注册“Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]”类型的服务 - No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered System.InvalidOperationException:“没有为类型 'Microsoft.AspNetCore.Hosting.Server.IServer' 注册服务。” - System.InvalidOperationException: 'No service for type 'Microsoft.AspNetCore.Hosting.Server.IServer' has been registered.' 没有为“Microsoft.AspNetCore.Identity.UserManager`1[testLogin.Areas.Identity.Data.testLoginUser]”类型注册服务 - No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[testLogin.Areas.Identity.Data.testLoginUser]' has been registered Microsoft.AspNetCore.Mvc.ViewFeatures.UnsupportedJavaScriptRuntime - Microsoft.AspNetCore.Mvc.ViewFeatures.UnsupportedJavaScriptRuntime 类型“Microsoft.AspNetCore.Hosting.Server.IServer”的没有服务已在.Net core 3.1 控制台应用程序中注册错误 - No service for type 'Microsoft.AspNetCore.Hosting.Server.IServer' has been registered error in .Net core 3.1 console app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM