首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MVC没有为该对象定义无参数构造函数

MVC没有为该对象定义无参数构造函数
EN

Stack Overflow用户
提问于 2017-09-02 20:41:08
回答 1查看 705关注 0票数 1

我一直在遵循https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db的步骤来创建一个项目,当我完成脚手架的最后一步时--一个实体的控制器--我会得到一个错误:“没有为这个对象定义的无参数构造函数”。我已经查看过来自堆栈溢出的链接,与ASP.NET MVC: No parameterless constructor defined for this object完全相同,但是我有一个无参数的构造函数,如下面的代码所示。

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
 var host = new WebHostBuilder()
          .UseKestrel()
          .UseContentRoot(Directory.GetCurrentDirectory())
          .UseIISIntegration()
          .UseStartup<Startup>()
          .UseApplicationInsights()
          .Build();
           host.Run();
EN

回答 1

Stack Overflow用户

发布于 2017-09-03 01:22:37

答案是我更新到.Net Core2.0,而我的program.cs仍然使用一种包含1.0的格式。我将代码更改为下面的代码,并且能够成功地创建控制器。

改为:

代码语言:javascript
运行
复制
          var host = new WebHostBuilder()
              .UseKestrel()
              .UseContentRoot(Directory.GetCurrentDirectory())
              .UseIISIntegration()
              .UseStartup<Startup>()
              .UseApplicationInsights()
              .Build();
               host.Run();

至:

代码语言:javascript
运行
复制
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46017996

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档