开发手册 欢迎您!
软件开发者资料库

ASP.NET Core ConfigureServices()中调用AddMvc()异常KeyNotFoundException

本文主要介绍ASP.NET Core中,在Startup.cs中ConfigureServices()方法中调用services.AddMvc()方法,出现异常(KeyNotFoundException: The given key was not present in the dictionary. )的解决方法。

1、项目中调用代码

public IServiceProvider ConfigureServices(IServiceCollection services){   // Add services to the collection.   services.AddMvc();}

抛出异常信息

KeyNotFoundException: The given key was not present in the dictionary. System.Collections.Generic.Dictionary.get_Item(TKey key) 
Microsoft.AspNetCore.Mvc.Internal.DefaultAssemblyPartDiscoveryProvider+CandidateResolver.ComputeClassification(string dependency) 
Microsoft.AspNetCore.Mvc.Internal.DefaultAssemblyPartDiscoveryProvider+CandidateResolver.ComputeClassification(string dependency) 
Microsoft.AspNetCore.Mvc.Internal.DefaultAssemblyPartDiscoveryProvider+CandidateResolver.ComputeClassification(string dependency) 
Microsoft.AspNetCore.Mvc.Internal.DefaultAssemblyPartDiscoveryProvider+CandidateResolver.ComputeClassification(string dependency) 
Microsoft.AspNetCore.Mvc.Internal.DefaultAssemblyPartDiscoveryProvider+CandidateResolver+d__4.MoveNext() System.Linq.Enumerable+d__17.MoveNext() System.Linq.Enumerable+WhereSelectEnumerableIterator.MoveNext() Microsoft.Extensions.DependencyInjection.MvcCoreServiceCollectionExtensions.GetApplicationPartManager(IServiceCollection services) 
Microsoft.Extensions.DependencyInjection.MvcCoreServiceCollectionExtensions.AddMvcCore(IServiceCollection services) 
Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddMvc(IServiceCollection services) MyWebApiProject.Startup.ConfigureServices(IServiceCollection services) in Startup.cs System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 
Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services) Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices() Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

csproj文件内容

net461
















2、解决方法

在添加MVC之前添加ApplicationPartManager

var manager = new ApplicationPartManager();
manager.ApplicationParts.Add(new AssemblyPart(typeof(Startup).Assembly));
services.AddSingleton(manager);
services.AddMvc();

参考文档https://github.com/aspnet/Home/issues/3132