ASP.NET Core WEB API配置文件问题

时间:2018-05-03 16:22:34

标签: asp.net-web-api asp.net-core config appsettings

我不确定这个问题是否与ASP.NET Core有关。

我在appsettings.json文件中定义了我的连接字符串并发布了API项目。

当我执行端点时,我收到此错误: “在应用程序配置文件中找不到名为'DbContext'的连接字符串。”,尽管我在appsettings.json中定义了DbContext

使其正常工作的唯一方法是显式指定projectname.exe.config文件中的连接字符串。知道为什么会这样吗?我不能只在appsettings.json中指定连接字符串,并在必要时从那里选择它吗?

以下是我的appsettings.json文件:

{
 "ConnectionStrings": {
"DbConnectionString": "data source=DEV-DB;initial catalog=AmsSystem;user id=sa;password=111111;multipleactiveresultsets=True;application name=EntityFramework",
"DbContext": "data source=DEV-DB;initial catalog=AmsSystem;user id=sa;password=111111;multipleactiveresultsets=True;application name=EntityFramework"
},
"AppSettings": {
"AESEncryptionKey": "qgJMnfoVGxwZsl8eELea5/1jqyQJg2mgC/Vb4mUetN4=",
"VirtualDirectory": "/demoapi"
},
"Logging": {
"IncludeScopes": false,
"Debug": {
  "LogLevel": {
    "Default": "Warning"
  }
},
"Console": {
  "LogLevel": {
    "Default": "Warning"
  }
}

},
 "JwtSecurityToken": {
"Key": "YouCannotAlterTokenIfYouCannotHoldThisVeryLongKey",
"Issuer": "http://demoserver.com",
"Audience": "http://demoserver.com"
}
 }

Program.cs的

 public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

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

Startup.cs

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

        services.AddScoped(_ => new DbContext());

        // get the application configuration settings
        var appSettings = config.GetSection("AppSettings");
        services.Configure<AppConfig>(appSettings);

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        // Add custom repositories
        services.AddTransient<IModelFactory, ModelFactory>();


        // Add custom services
        services.AddTransient<IAppointmentProvider, AppointmentDataProvider>();
        services.AddTransient<ILogProvider, EventLogProvider>();

        // add the database connection
        services.AddDbContext<SecurityContext>(options =>
    options.UseSqlServer(config.GetConnectionString("DbConnectionString")));

        // add ASP.NET identity service
        services.AddIdentity<ApiUser, ApiRole>()
            .AddEntityFrameworkStores<SecurityContext>()
            .AddDefaultTokenProviders();
}

0 个答案:

没有答案