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

点点圈 提交于 2019-11-30 00:11:52

问题


I'm having this problem: No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered. In asp.net core 1.0, it seems that when the action try to render the view i have that exception.

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

{
  "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

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?}");
        }
    }
}

回答1:


Solution: Use AddMvc() instead of AddMvcCore() in Startup.cs and it will work.

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.

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.

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

You might also have to add a reference toMicrosoft.AspNetCore.Mvc.ViewFeature in project.json

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




回答2:


If you're using 2.0 then use services.AddMvcCore().AddRazorViewEngine(); in your ConfigureServices

Also remember to add .AddAuthorization() if you're using Authorize attribute, otherwise it won't work.




回答3:


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. Making my Startup.cs look like this fixed it for me:

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();
        });
    }
}



回答4:


For .NET Core 2.0, in ConfigureServices, use :

services.AddNodeServices();



回答5:


Just add following code and it should work:

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

        }



回答6:


For those that get this issue during .NetCore 1.X -> 2.0 upgrade, update both your Program.cs and Startup.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
    }
}



回答7:


This one works for my case :

services.AddMvcCore()
.AddApiExplorer();



回答8:


You use this in startup.cs

services.AddSingleton<PartialViewResultExecutor>();



回答9:


To be able to return JSON data, JsonFormatterServices need to be registered with the dependency injection container. AddMvc() method does this but not the AddMvcCore() method. You can confirm this by looking at the source code on ASP.NET Core MVC Github page.



来源:https://stackoverflow.com/questions/38709538/no-service-for-type-microsoft-aspnetcore-mvc-viewfeatures-itempdatadictionaryfa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!