配置文件 'appsettings.json' 未找到并且不是可选的
The configuration file 'appsettings.json' was not found and is not optional
Azure 错误是:
.Net Core: Application startup exception:
System.IO.FileNotFoundException: The configuration file
'appsettings.json' was not found and is not optional.
所以这有点含糊。我似乎无法确定这一点。我正在尝试将 .Net Core Web API 项目部署到 Azure,但出现此错误:
:( Oops. 500 Internal Server Error
An error occurred while starting the application.
我已经部署了普通的老式 .Net WebAPI,它们运行良好。我已经按照在线教程进行操作,并且它们已经奏效了。但不知何故我的项目坏了。在 Web.config 上启用 stdoutLogEnabled 并查看 Azure 流式处理日志给我这样的信息:
2016-08-26T02:55:12 Welcome, you are now connected to log-streaming service.
Application startup exception: System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional.
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load()
at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
at Quanta.API.Startup..ctor(IHostingEnvironment env) in D:\Source\Workspaces\Quanta\src\Quanta.API\Startup.cs:line 50
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.Extensions.Internal.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
at Microsoft.AspNetCore.Hosting.Internal.StartupLoader.LoadMethods(IServiceProvider services, Type startupType, String environmentName)
at Microsoft.AspNetCore.Hosting.WebHostBuilderExtensions.<>c__DisplayClass1_0.<UseStartup>b__1(IServiceProvider sp)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryService.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.SingletonCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass12_0.<RealizeService>b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureStartup()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Hosting environment: Production
Content root path: D:\home\site\wwwroot
Now listening on: http://localhost:30261
Application started. Press Ctrl+C to shut down.
好的,这看起来很简单。它找不到 appsettings.json。查看我的配置 ( startup.cs ) 它似乎定义得很好。我的启动看起来像这样:
public class Startup
{
private static string _applicationPath = string.Empty;
private static string _contentRootPath = string.Empty;
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
_applicationPath = env.WebRootPath;
_contentRootPath = env.ContentRootPath;
// Setup configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(_contentRootPath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// This reads the configuration keys from the secret store.
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
private string GetXmlCommentsPath()
{
var app = PlatformServices.Default.Application;
return System.IO.Path.Combine(app.ApplicationBasePath, "Quanta.API.xml");
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
var pathToDoc = GetXmlCommentsPath();
services.AddDbContext<QuantaContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"],
b => b.MigrationsAssembly("Quanta.API")));
//Swagger
services.AddSwaggerGen();
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "Project Quanta API",
Description = "Quant.API",
TermsOfService = "None"
});
options.IncludeXmlComments(pathToDoc);
options.DescribeAllEnumsAsStrings();
});
// Repositories
services.AddScoped<ICheckListRepository, CheckListRepository>();
services.AddScoped<ICheckListItemRepository, CheckListItemRepository>();
services.AddScoped<IClientRepository, ClientRepository>();
services.AddScoped<IDocumentRepository, DocumentRepository>();
services.AddScoped<IDocumentTypeRepository, DocumentTypeRepository>();
services.AddScoped<IProjectRepository, ProjectRepository>();
services.AddScoped<IProtocolRepository, ProtocolRepository>();
services.AddScoped<IReviewRecordRepository, ReviewRecordRepository>();
services.AddScoped<IReviewSetRepository, ReviewSetRepository>();
services.AddScoped<ISiteRepository, SiteRepository>();
// Automapper Configuration
AutoMapperConfiguration.Configure();
// Enable Cors
services.AddCors();
// Add MVC services to the services container.
services.AddMvc()
.AddJsonOptions(opts =>
{
// Force Camel Case to JSON
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
// Add MVC to the request pipeline.
app.UseCors(builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
}
});
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
// Uncomment the following line to add a route for porting Web API 2 controllers.
//routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
});
//Ensure DB is created, and latest migration applied. Then seed.
using (var serviceScope = app.ApplicationServices
.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
QuantaContext dbContext = serviceScope.ServiceProvider.GetService<QuantaContext>();
dbContext.Database.Migrate();
QuantaDbInitializer.Initialize(dbContext);
}
app.UseSwagger();
app.UseSwaggerUi();
}
}
这在本地工作正常。但是一旦我们发布到 Azure,就会失败。我不知所措。我已经创建了部署到 Azure 的新 .Net 核心项目。但是我投入所有时间的这个项目似乎失败了。我正准备将无法 运行 的项目中的代码复制并粘贴到新项目中,但我真的很好奇是什么破坏了它。
有什么想法吗?
编辑:
所以我的 Program.cs 是:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace Quanta.API
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
编辑2:
Per Frans,我检查了 publishOptions。它是:
"publishOptions": {
"include": [
"wwwroot",
"web.config"
]
我从一个工作项目中获取了一个 publishOptions 并将其更改为:
"publishOptions": {
"include": [
"wwwroot",
"Views",
"Areas/**/Views",
"appsettings.json",
"web.config"
]
},
它仍然给出了 500 错误,但它没有给出堆栈跟踪说明它可以加载 appsettings.json。现在它正在抱怨与 SQL 的连接。我注意到很多 RC1 博客文章中都提到了我的 SQL 连接字符串代码。 .Net Core 的 RC2 改变了它。所以我将其更新为:
"Data": {
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\MSSQLLocalDB;Database=QuantaDb;Trusted_Connection=True;MultipleActiveResultSets=true"
}
},
并将我的启动更改为:
services.AddDbContext<QuantaContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
b => b.MigrationsAssembly("Quanta.API")));
终于成功了。
我一定是遵循了一个较早的 RC1 示例,但没有意识到。
检查 project.json 中的 publishOptions 并确保 "include" 部分包含 "appsettings.json"。
他们更改了 RTM 中的发布模型,要求您指定要从编译目录复制到 Web 文件夹的所有内容。
编辑:请参阅下面的 Jensdc 回答,了解如何在 project.json 被杀后使用 .csproj 执行此操作。
在你的project.json
确保您已将 appsettings.json
作为 copyToOutput
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true,
"copyToOutput": {
"include": [ "appsettings.json" ]
}
},
在后来的 .net 核心版本中,使用 *.csproj 文件代替 project.json 文件。
您可以修改文件以获得所需的结果,方法是添加:
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
您无需添加 .json 文件即可发布选项。
只是它在错误的路径中查找文件。
设置基本路径,然后添加 json 文件即可。
public Startup(IHostingEnvironment environment)
{
var builder = new ConfigurationBuilder()
.SetBasePath(environment.ContentRootPath)
.AddJsonFile("TestJson.json");
Configuration = builder.Build();
}
此处,启动构造函数是使用 HostingEnviornment 构建的,基本路径设置为当前根路径。
它会起作用的!
对我来说,解决的问题是设置在输出目录(Build 目录)中包含 appsettings.json
via interface,如下所示:
在我的例子中,文件 appsettings.json
存在于项目文件夹中,但它被设置为 Do not copy
,我将设置更改为 Copy always
(见下图)。它对我有用。
它会自动将以下 XML 添加到您的 project.csproj
文件中:
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
我看过其他答案,project.json
已经死了,正如 answer 所说。
对我来说,我收到此错误是因为 JSON 文件语法错误(拼写错误:删除逗号)。
默认情况下,appsettings.json 的 属性 "Copy to Output Directory" 设置为我认为正确的 "Do not Copy"。
对我来说,错误是使用 Directory.GetCurrentDirectory()
。这在本地 运行 工作正常,但在生产服务器上,当程序从 Powershell
启动时它失败了。替换为 Assembly.GetEntryAssembly().Location
,一切正常。
完整代码:
var builder = new ConfigurationBuilder()
.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
我在 Visual Studio 2019 年发布我的 Azure 函数时最终来到这里。我在尝试使用 appSettings.json 文件将我的函数发布到门户时遇到此错误。它正在将 appSettings.json 复制到 output 目录而不是 publish 目录。我必须将下面的行添加到 azure 函数项目的 .csproj 中。
<CopyToPublishDirectory>Always</CopyToPublishDirectory>
所以我的 .csproj 如下所示:
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>Always</CopyToPublishDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
此答案适用于...有人试图在 VS Code 上进行调试,但 appsettings.json 未被选中。我尝试在 Visual Studio 中调试相同的解决方案,它成功了。
另外,我能够访问环境变量。应用版本:Core 2.2.
我删除了 .vscode 文件夹并再次调试,它成功了。
对我有用的是将 appsettings.json
上的 复制到输出目录 属性 更改为 如果较新则复制.
在使用 .net core 3 时遇到同样的问题,这是有效的。
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
希望这是好的
当应用程序从网络共享 运行 时,我遇到了同样的错误。它甚至试图在用户的桌面上找到 appsettings.json
文件。
我最终将路径与可执行位置结合起来,如下所示:
configuration
.AddJsonFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json"), optional: false, reloadOnChange: false)
.AddJsonFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"appsettings.{env.EnvironmentName}.json"), optional: true, reloadOnChange: false);
对我来说,问题是 appsettings.json 文件被隐藏了。我不知道它是如何被隐藏的,但 .netcore ConfiguraitonFileProvider 会检查隐藏文件,如果它们被隐藏,则不会加载它们。
Azure 错误是:
.Net Core: Application startup exception: System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional.
所以这有点含糊。我似乎无法确定这一点。我正在尝试将 .Net Core Web API 项目部署到 Azure,但出现此错误:
:( Oops. 500 Internal Server Error An error occurred while starting the application.
我已经部署了普通的老式 .Net WebAPI,它们运行良好。我已经按照在线教程进行操作,并且它们已经奏效了。但不知何故我的项目坏了。在 Web.config 上启用 stdoutLogEnabled 并查看 Azure 流式处理日志给我这样的信息:
2016-08-26T02:55:12 Welcome, you are now connected to log-streaming service.
Application startup exception: System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional.
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load()
at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
at Quanta.API.Startup..ctor(IHostingEnvironment env) in D:\Source\Workspaces\Quanta\src\Quanta.API\Startup.cs:line 50
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.Extensions.Internal.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
at Microsoft.AspNetCore.Hosting.Internal.StartupLoader.LoadMethods(IServiceProvider services, Type startupType, String environmentName)
at Microsoft.AspNetCore.Hosting.WebHostBuilderExtensions.<>c__DisplayClass1_0.<UseStartup>b__1(IServiceProvider sp)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryService.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.SingletonCallSite.Invoke(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass12_0.<RealizeService>b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureStartup()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Hosting environment: Production
Content root path: D:\home\site\wwwroot
Now listening on: http://localhost:30261
Application started. Press Ctrl+C to shut down.
好的,这看起来很简单。它找不到 appsettings.json。查看我的配置 ( startup.cs ) 它似乎定义得很好。我的启动看起来像这样:
public class Startup
{
private static string _applicationPath = string.Empty;
private static string _contentRootPath = string.Empty;
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
_applicationPath = env.WebRootPath;
_contentRootPath = env.ContentRootPath;
// Setup configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(_contentRootPath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// This reads the configuration keys from the secret store.
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
private string GetXmlCommentsPath()
{
var app = PlatformServices.Default.Application;
return System.IO.Path.Combine(app.ApplicationBasePath, "Quanta.API.xml");
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
var pathToDoc = GetXmlCommentsPath();
services.AddDbContext<QuantaContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"],
b => b.MigrationsAssembly("Quanta.API")));
//Swagger
services.AddSwaggerGen();
services.ConfigureSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "Project Quanta API",
Description = "Quant.API",
TermsOfService = "None"
});
options.IncludeXmlComments(pathToDoc);
options.DescribeAllEnumsAsStrings();
});
// Repositories
services.AddScoped<ICheckListRepository, CheckListRepository>();
services.AddScoped<ICheckListItemRepository, CheckListItemRepository>();
services.AddScoped<IClientRepository, ClientRepository>();
services.AddScoped<IDocumentRepository, DocumentRepository>();
services.AddScoped<IDocumentTypeRepository, DocumentTypeRepository>();
services.AddScoped<IProjectRepository, ProjectRepository>();
services.AddScoped<IProtocolRepository, ProtocolRepository>();
services.AddScoped<IReviewRecordRepository, ReviewRecordRepository>();
services.AddScoped<IReviewSetRepository, ReviewSetRepository>();
services.AddScoped<ISiteRepository, SiteRepository>();
// Automapper Configuration
AutoMapperConfiguration.Configure();
// Enable Cors
services.AddCors();
// Add MVC services to the services container.
services.AddMvc()
.AddJsonOptions(opts =>
{
// Force Camel Case to JSON
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.UseStaticFiles();
// Add MVC to the request pipeline.
app.UseCors(builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
}
});
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
// Uncomment the following line to add a route for porting Web API 2 controllers.
//routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
});
//Ensure DB is created, and latest migration applied. Then seed.
using (var serviceScope = app.ApplicationServices
.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
QuantaContext dbContext = serviceScope.ServiceProvider.GetService<QuantaContext>();
dbContext.Database.Migrate();
QuantaDbInitializer.Initialize(dbContext);
}
app.UseSwagger();
app.UseSwaggerUi();
}
}
这在本地工作正常。但是一旦我们发布到 Azure,就会失败。我不知所措。我已经创建了部署到 Azure 的新 .Net 核心项目。但是我投入所有时间的这个项目似乎失败了。我正准备将无法 运行 的项目中的代码复制并粘贴到新项目中,但我真的很好奇是什么破坏了它。
有什么想法吗?
编辑: 所以我的 Program.cs 是:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace Quanta.API
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
编辑2: Per Frans,我检查了 publishOptions。它是:
"publishOptions": {
"include": [
"wwwroot",
"web.config"
]
我从一个工作项目中获取了一个 publishOptions 并将其更改为:
"publishOptions": {
"include": [
"wwwroot",
"Views",
"Areas/**/Views",
"appsettings.json",
"web.config"
]
},
它仍然给出了 500 错误,但它没有给出堆栈跟踪说明它可以加载 appsettings.json。现在它正在抱怨与 SQL 的连接。我注意到很多 RC1 博客文章中都提到了我的 SQL 连接字符串代码。 .Net Core 的 RC2 改变了它。所以我将其更新为:
"Data": {
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\MSSQLLocalDB;Database=QuantaDb;Trusted_Connection=True;MultipleActiveResultSets=true"
}
},
并将我的启动更改为:
services.AddDbContext<QuantaContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
b => b.MigrationsAssembly("Quanta.API")));
终于成功了。
我一定是遵循了一个较早的 RC1 示例,但没有意识到。
检查 project.json 中的 publishOptions 并确保 "include" 部分包含 "appsettings.json"。 他们更改了 RTM 中的发布模型,要求您指定要从编译目录复制到 Web 文件夹的所有内容。
编辑:请参阅下面的 Jensdc 回答,了解如何在 project.json 被杀后使用 .csproj 执行此操作。
在你的project.json
确保您已将 appsettings.json
作为 copyToOutput
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true,
"copyToOutput": {
"include": [ "appsettings.json" ]
}
},
在后来的 .net 核心版本中,使用 *.csproj 文件代替 project.json 文件。
您可以修改文件以获得所需的结果,方法是添加:
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
您无需添加 .json 文件即可发布选项。 只是它在错误的路径中查找文件。
设置基本路径,然后添加 json 文件即可。
public Startup(IHostingEnvironment environment)
{
var builder = new ConfigurationBuilder()
.SetBasePath(environment.ContentRootPath)
.AddJsonFile("TestJson.json");
Configuration = builder.Build();
}
此处,启动构造函数是使用 HostingEnviornment 构建的,基本路径设置为当前根路径。 它会起作用的!
对我来说,解决的问题是设置在输出目录(Build 目录)中包含 appsettings.json
via interface,如下所示:
在我的例子中,文件 appsettings.json
存在于项目文件夹中,但它被设置为 Do not copy
,我将设置更改为 Copy always
(见下图)。它对我有用。
它会自动将以下 XML 添加到您的 project.csproj
文件中:
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
我看过其他答案,project.json
已经死了,正如 answer 所说。
对我来说,我收到此错误是因为 JSON 文件语法错误(拼写错误:删除逗号)。
默认情况下,appsettings.json 的 属性 "Copy to Output Directory" 设置为我认为正确的 "Do not Copy"。
对我来说,错误是使用 Directory.GetCurrentDirectory()
。这在本地 运行 工作正常,但在生产服务器上,当程序从 Powershell
启动时它失败了。替换为 Assembly.GetEntryAssembly().Location
,一切正常。
完整代码:
var builder = new ConfigurationBuilder()
.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
我在 Visual Studio 2019 年发布我的 Azure 函数时最终来到这里。我在尝试使用 appSettings.json 文件将我的函数发布到门户时遇到此错误。它正在将 appSettings.json 复制到 output 目录而不是 publish 目录。我必须将下面的行添加到 azure 函数项目的 .csproj 中。
<CopyToPublishDirectory>Always</CopyToPublishDirectory>
所以我的 .csproj 如下所示:
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>Always</CopyToPublishDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
此答案适用于...有人试图在 VS Code 上进行调试,但 appsettings.json 未被选中。我尝试在 Visual Studio 中调试相同的解决方案,它成功了。 另外,我能够访问环境变量。应用版本:Core 2.2.
我删除了 .vscode 文件夹并再次调试,它成功了。
对我有用的是将 appsettings.json
上的 复制到输出目录 属性 更改为 如果较新则复制.
在使用 .net core 3 时遇到同样的问题,这是有效的。
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
希望这是好的
当应用程序从网络共享 运行 时,我遇到了同样的错误。它甚至试图在用户的桌面上找到 appsettings.json
文件。
我最终将路径与可执行位置结合起来,如下所示:
configuration
.AddJsonFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json"), optional: false, reloadOnChange: false)
.AddJsonFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"appsettings.{env.EnvironmentName}.json"), optional: true, reloadOnChange: false);
对我来说,问题是 appsettings.json 文件被隐藏了。我不知道它是如何被隐藏的,但 .netcore ConfiguraitonFileProvider 会检查隐藏文件,如果它们被隐藏,则不会加载它们。