.NET Core 的版本是 3.1
遇到的问题是 Action 中 return View() 的时候报错

An unhandled exception occurred while processing the request.

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

Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)

错误内容的字面意思是 ITempDataDictionaryFactory 这玩意没有注册。

解决方案一:

修改 Startup.cs 中的 ConfigureServices方法

        public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}

解决方案二:
修改 Startup.cs 中的 ConfigureServices方法

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

查看AspNetCore.Mvc 的源码

        public static IMvcBuilder AddMvc(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
} services.AddControllersWithViews();
return services.AddRazorPages();
}

AddMvc 方法中包含了 AddControllersWithViews
        public static IMvcBuilder AddControllersWithViews(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
} var builder = AddControllersWithViewsCore(services);
return new MvcBuilder(builder.Services, builder.PartManager);
}

跳转到 AddControllersWithViewsCore

        private static IMvcCoreBuilder AddControllersWithViewsCore(IServiceCollection services)
{
var builder = AddControllersCore(services)
.AddViews()
.AddRazorViewEngine()
.AddCacheTagHelper(); AddTagHelpersFrameworkParts(builder.PartManager); return builder;
}

跳转到 AddViews

        public static IMvcCoreBuilder AddViews(this IMvcCoreBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
} builder.AddDataAnnotations();
AddViewComponentApplicationPartsProviders(builder.PartManager);
AddViewServices(builder.Services);
return builder;
}

跳转到 AddViewServices

        internal static void AddViewServices(IServiceCollection services)
{
services.AddDataProtection();
services.AddAntiforgery();
services.AddWebEncoders(); services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcViewOptions>, MvcViewOptionsSetup>());
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, TempDataMvcOptionsSetup>()); //
// View Engine and related infrastructure
//
services.TryAddSingleton<ICompositeViewEngine, CompositeViewEngine>();
services.TryAddSingleton<IActionResultExecutor<ViewResult>, ViewResultExecutor>();
services.TryAddSingleton<IActionResultExecutor<PartialViewResult>, PartialViewResultExecutor>(); // Support for activating ViewDataDictionary
services.TryAddEnumerable(
ServiceDescriptor
.Transient<IControllerPropertyActivator, ViewDataDictionaryControllerPropertyActivator>()); //
// HTML Helper
//
services.TryAddTransient<IHtmlHelper, HtmlHelper>();
services.TryAddTransient(typeof(IHtmlHelper<>), typeof(HtmlHelper<>));
services.TryAddSingleton<IHtmlGenerator, DefaultHtmlGenerator>();
services.TryAddSingleton<ModelExpressionProvider>();
// ModelExpressionProvider caches results. Ensure that it's re-used when the requested type is IModelExpressionProvider.
services.TryAddSingleton<IModelExpressionProvider>(s => s.GetRequiredService<ModelExpressionProvider>());
services.TryAddSingleton<ValidationHtmlAttributeProvider, DefaultValidationHtmlAttributeProvider>(); services.TryAddSingleton<IJsonHelper, SystemTextJsonHelper>(); // Component services for Blazor server-side interop
services.TryAddSingleton<ServerComponentSerializer>(); //
// View Components
// // These do caching so they should stay singleton
services.TryAddSingleton<IViewComponentSelector, DefaultViewComponentSelector>();
services.TryAddSingleton<IViewComponentFactory, DefaultViewComponentFactory>();
services.TryAddSingleton<IViewComponentActivator, DefaultViewComponentActivator>();
services.TryAddSingleton<
IViewComponentDescriptorCollectionProvider,
DefaultViewComponentDescriptorCollectionProvider>();
services.TryAddSingleton<IActionResultExecutor<ViewComponentResult>, ViewComponentResultExecutor>(); services.TryAddSingleton<ViewComponentInvokerCache>();
services.TryAddTransient<IViewComponentDescriptorProvider, DefaultViewComponentDescriptorProvider>();
services.TryAddSingleton<IViewComponentInvokerFactory, DefaultViewComponentInvokerFactory>();
services.TryAddTransient<IViewComponentHelper, DefaultViewComponentHelper>(); //
// Temp Data
//
services.TryAddEnumerable(
ServiceDescriptor.Transient<IApplicationModelProvider, TempDataApplicationModelProvider>());
services.TryAddEnumerable(
ServiceDescriptor.Transient<IApplicationModelProvider, ViewDataAttributeApplicationModelProvider>());
services.TryAddSingleton<SaveTempDataFilter>(); //
// Component rendering
//
services.TryAddScoped<IComponentRenderer, ComponentRenderer>();
services.TryAddScoped<StaticComponentRenderer>();
services.TryAddScoped<NavigationManager, HttpNavigationManager>();
services.TryAddScoped<IJSRuntime, UnsupportedJavaScriptRuntime>();
services.TryAddScoped<INavigationInterception, UnsupportedNavigationInterception>(); services.TryAddTransient<ControllerSaveTempDataPropertyFilter>(); // This does caching so it should stay singleton
services.TryAddSingleton<ITempDataProvider, CookieTempDataProvider>();
services.TryAddSingleton<TempDataSerializer, DefaultTempDataSerializer>(); //
// Antiforgery
//
services.TryAddSingleton<ValidateAntiforgeryTokenAuthorizationFilter>();
services.TryAddSingleton<AutoValidateAntiforgeryTokenAuthorizationFilter>(); // These are stateless so their lifetime isn't really important.
services.TryAddSingleton<ITempDataDictionaryFactory, TempDataDictionaryFactory>();
services.TryAddSingleton(ArrayPool<ViewBufferValue>.Shared);
services.TryAddScoped<IViewBufferScope, MemoryPoolViewBufferScope>();
}

找到了 services.TryAddSingleton<ITempDataDictionaryFactory, TempDataDictionaryFactory>();

这一段绑定的代码。

Core 3.1 MVC 抛异常“InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered.”的更多相关文章

  1. TypeLoadException: Could not load type 'Microsoft.AspNetCore.Mvc.Internal.IHttpResponseStreamWriterFactory' from assembly 'Microsoft.AspNetCore.Mvc.Core, Version=2.1.2.0 ...

    今天调试 asp.net core 2.0 项目时遇到了如下错误: TypeLoadException: Could not load type 'Microsoft.AspNetCore.Mvc.I ...

  2. InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'

    在新建asp.net core 应用后, 添加了自定义的ApplicationDbContext 和ApplicationUser ,并添加了Identity认证后, 会出现 InvalidOpera ...

  3. Orchard Core 版本冲突 The type 'FormTagHelper' exists in both 'Microsoft.AspNetCore.Mvc.TagHelpers, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' and...

    最近老大让我看Orchard Core,这是一个CMS系统.可以先参考大佬的文章:https://www.cnblogs.com/shanyou/archive/2018/09/25/9700422. ...

  4. .net core 3.0web_razor page项目_使用中间件接受大文件上传报错_httpRequest.Form threw an exception of type Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException_Request body too large

    前言:在web项目的.net framework时文件上传时,自己常用一般处理程序接受上传文件,上传文件的大小限制是可以项目的webconfig里配置.   到core项目使用一般处理程序变成了中间件 ...

  5. API服务版本控制 Microsoft.AspNetCore.Mvc.Versioning

    我们在进行webapi服务开发时,会遇到一些多个版本的api共存的情况发生,例如某一版本APP上线后,需求发生变更,需要在下一个升级版本更新API,但同时又需要保证这个APP版本能正常使用,这时候就需 ...

  6. MVC中异常: An exception of type 'System.Data.ProviderIncompatibleException' occurred in EntityFramework.dll的一种解决办法

    今天在调试MVC的例子的时候,总是出错(An exception of type 'System.Data.ProviderIncompatibleException' occurred in Ent ...

  7. 由ASP.NET Core根据路径下载文件异常引发的探究

    前言 最近在开发新的项目,使用的是ASP.NET Core6.0版本的框架.由于项目中存在文件下载功能,没有使用类似MinIO或OSS之类的分布式文件系统,而是下载本地文件,也就是根据本地文件路径进行 ...

  8. .NET Core整合log4net以及全局异常捕获实现

    在使用log4net之前先安装log4net.这里操作很简单,通过nuget下载并安装log4net很方便.如下图. log4net配置 <?xml version="1.0" ...

  9. ASP.NET Core Web 应用程序系列(二)- 在ASP.NET Core中使用Autofac替换自带DI进行批量依赖注入(MVC当中应用)

    在上一章中主要和大家分享在MVC当中如何使用ASP.NET Core内置的DI进行批量依赖注入,本章将继续和大家分享在ASP.NET Core中如何使用Autofac替换自带DI进行批量依赖注入. P ...

随机推荐

  1. 【LeetCode】846. Hand of Straights 解题报告(Python & C+)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  2. 【LeetCode】703. Kth Largest Element in a Stream 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 小根堆 日期 题目地址:https://leetco ...

  3. A. Watchmen(Codeforces 650A)

    A. Watchmen time limit per test 3 seconds memory limit per test 256 megabytes input standard input o ...

  4. Inverse/Implicit Function Theorem

    目录 4.1 The Inverse Function Theorem The Implicit Function Theorem 4.3 Curves and Surfaces 4.4 The Mo ...

  5. 取代 Maven?这款项目构建工具性能提升 300%

    在 GitHub 上闲逛的时候,发现了一个新的项目:maven-mvnd,持续霸占 GitHub trending 榜单好几天了. maven-mvnd,可以读作 Maven Daemon,译作 Ma ...

  6. MySQL数据库基础(2)表结构管理

    目录 一.关系模型与数据表 二.MySQL数据类型 三.数据完整性约束 四.参照完整性约束 一.关系模型与数据表 概念 ①关系模型:是由若干个关系模式组成的集合,关系模式的实例称为关系,每个关系实际上 ...

  7. 论文翻译:2020_Generative Adversarial Network based Acoustic Echo Cancellation

    论文地址:http://www.interspeech2020.org/uploadfile/pdf/Thu-1-10-5.pdf 基于GAN的回声消除 摘要 生成对抗网络(GANs)已成为语音增强( ...

  8. 解决VirtualBox 运行时报内存不能written

    在VirtualBox 虚拟机中安装系统的时候,突然报"0x00000000指令,该内存不能written",只能强制停止,这个问题要怎么解决呢? 解决办法是恢复系统主题3个dll ...

  9. spring-Ioc(二)学习笔记

    属性注入方式 设值注入:也就是set注入,通过setter方法注入 java Bean private ITestDao dao; public void setDao(ITestDao dao){ ...

  10. VC 2010 Express 学生版(中文版)

    Microsoft Visual C++ 2010 Express 学生版 下载传送门(提取码:r7sm) 如何安装 拿到压缩文件后,解压到桌面(别怕,安装完后这个文件夹是可以删除的). 在 &quo ...