【问题标题】:MVC no parameterless constructor defined for this objectMVC 没有为此对象定义无参数构造函数
【发布时间】:2018-02-11 13:36:27
【问题描述】:

我一直按照https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db 的步骤创建项目,当我到达为我的一个实体搭建控制器的最后一步时,我收到错误“没有为此对象定义无参数构造函数”。我已经查看了来自 stackoverflow 的链接以解决完全相同的问题 ASP.NET MVC: No parameterless constructor defined for this object,但我有一个无参数构造函数,如下面的代码所示。

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

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

        var connection = "connection string here";
        services.AddDbContext<SchoolManagementContext>(options => options.UseSqlServer(connection));
    }

    // 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)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseMvc();
    }

}

}

program.cs

 var host = new WebHostBuilder()
          .UseKestrel()
          .UseContentRoot(Directory.GetCurrentDirectory())
          .UseIISIntegration()
          .UseStartup<Startup>()
          .UseApplicationInsights()
          .Build();
           host.Run();

【问题讨论】:

    标签: c# entity-framework asp.net-core asp.net-core-mvc


    【解决方案1】:

    答案是我更新到 .Net Core 2.0,而我的 program.cs 仍在使用涉及 1.0 的格式。我将代码更改为以下代码,并且能够成功创建控制器。

    更改自:

              var host = new WebHostBuilder()
                  .UseKestrel()
                  .UseContentRoot(Directory.GetCurrentDirectory())
                  .UseIISIntegration()
                  .UseStartup<Startup>()
                  .UseApplicationInsights()
                  .Build();
                   host.Run();
    

    到:

        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }
    
        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-21
      • 2010-11-24
      • 2013-04-25
      • 2017-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多