InvalidOperationException was unhandled by user code

InvalidOperationException was unhandled by user code

An exception of type 'System.InvalidOperationException' occurred in Microsoft.AspNet.Mvc.Core.dll but was not handled in user code


Additional information: Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddMvc()' inside the call to 'IApplicationBuilder.ConfigureServices(...)' or 'IApplicationBuilder.UseMvc(...)' in the application startup code.


InvalidOperationException was unhandled by user code

用户代码中存在未处理的无效操作异常

用户代码中存在没有处理的'System.InvalidOperationException'类型的异常出现在Microsoft.AspNet.Mvc.Core.dll中。

附加信息: 无法找到服务添加所有必需服务通过调用'IServiceCollection.AddMvc()'在'IApplicationBuilder.ConfigureServices(...)'内部

'IApplicationBuilder.UseMvc(...)' 应用程序启动代码中调用

产生异常的文件为“setup.cs”,代码如下:

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Framework.DependencyInjection;

public class Startup
{
    public void Configure(IApplicationBuilder app)
	{
		app.UseDefaultFiles();
		app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });   
    }

    public static void Main(string[] args) => WebApplication.Run(args);
}
在app.UseMvc处出错了,能看懂错误提示中的附加信息的话,应该已经大概明白了怎么处理。

我们把出错的代码加个Try catch处理,得到具体的错误信息:

InvalidOperationException was unhandled by user code
发现和上面给出的附加信息是一样的。


所以调试运行的时候产生未处理的异常,不要急着复制第一句错误信息“An exception of type 'System.InvalidOperationException' occurred in Microsoft.AspNet.Mvc.Core.dll but was not handled in user code”去搜索,对于类似 的错误这通常找到的答案都不是你想要的,因为这种类似的异常太多了。而应该去搜索附加信息Additional information: 后面的内容,那才是真实的错误信息。


那么上面的这个问题怎么解决呢?

啥也不说了,上代码:

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Framework.DependencyInjection;

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(Microsoft.Extensions.DependencyInjection.IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app)
	{
		app.UseDefaultFiles();
		app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

    }

    public static void Main(string[] args) => WebApplication.Run(args);
}
=========================分隔线====================================

如果自己没有尽力,就没有资格批评别人不用心。开口抱怨很容易,但是闭嘴努力的人,更加值得尊敬。