没有为“Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory”类型提供服务

时间:2016-08-01 23:22:54

标签: c# asp.net asp.net-mvc asp.net-core-1.0

我遇到了这个问题:没有为“Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory”类型的服务注册。在asp.net核心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?}");
        }
    }
}

12 个答案:

答案 0 :(得分:41)

解决方案:在AddMvc()中使用AddMvcCore()代替Startup.cs,它将有效。

有关原因的详细信息,请参阅此问题:

  

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

     

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

     

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

您可能还需要添加引用 到Microsoft.AspNetCore.Mvc.ViewFeature

中的project.json

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

答案 1 :(得分:21)

如果您使用2.0,请在services.AddMvcCore().AddRazorViewEngine();

中使用ConfigureServices

如果您使用.AddAuthorization()属性,请务必添加Authorize,否则无效。

答案 2 :(得分:9)

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

services.AddRazorPages();

ConfigureServices()

Configure()Startup.cs中的以下内容

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

答案 3 :(得分:6)

我知道这是一篇旧文章,但这是将MVC项目迁移到.NET Core 3.0后遇到的最高的Google搜索结果。使我的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();
        });
    }
}

答案 4 :(得分:2)

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

此代码已针对asp.net core 3.1(MVC)进行了测试

答案 5 :(得分:1)

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

services.AddNodeServices();

答案 6 :(得分:1)

现在我有同样的问题,我像你一样使用AddMcvCore。我发现错误是自我描述的,这是作为一个假设,我将AddControllersWithViews服务添加到ConfigureServices函数中,并为我解决了问题。 (我仍然也使用AddMvcCore。)

router.get('/services', (req, res) => {

    let arr = [];

    const call1 = service1()
        .then(res => arr.push({ res, type: 'service1'} ))
        .catch(error => res.status(error.status).json(error));

    const call2 = service2()
        .then(res => arr.push({ res, type: 'service2'} ))
        .catch(error => res.status(error.status).json(error));
})

Promise.all([service1, service2]).then(values => { 
  // not sure what to do here
});

答案 7 :(得分:0)

只需添加以下代码即可:

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

        }

答案 8 :(得分:0)

对于那些在.NetCore 1.X期间遇到此问题的人 - &gt; 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
    }
}

答案 9 :(得分:0)

这个适合我的情况:

services.AddMvcCore()
.AddApiExplorer();

答案 10 :(得分:0)

您在startup.cs中使用它

services.AddSingleton<PartialViewResultExecutor>();

答案 11 :(得分:0)

要能够返回JSON数据,JsonFormatterServices需要在依赖项注入容器中注册。 AddMvc()方法执行此操作,但AddMvcCore()方法则不执行此操作。您可以通过查看ASP.NET Core MVC Github页面上的源代码来确认这一点。