【问题标题】:The configuration file 'appsettings.json' was not found and is not optional未找到配置文件“appsettings.json”且不是可选的
【发布时间】:2017-01-02 14:58:11
【问题描述】:

Azure 错误是:

.Net Core:应用程序启动异常: System.IO.FileNotFoundException:配置文件 'appsettings.json' 未找到且不是可选的。

所以这有点模糊。我似乎无法确定这一点。我正在尝试将 .Net Core Web API 项目部署到 Azure,但出现此错误:

:( 糟糕。500 内部服务器错误 启动应用程序时出错。

我已经部署了普通的旧 .Net WebAPI,它们已经工作了。我已经按照在线教程进行了操作,并且它们已经奏效。但不知何故,我的项目坏了。在 Web.config 上启用 stdoutLogEnabled 并查看 Azure Streaming Logs 给了我这个:

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 ),它似乎定义得很好。我的 Startup 看起来像这样:

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: 根据 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 示例而没有意识到它。

【问题讨论】:

  • 在错误信息中有Content root path: D:\home\site\wwwroot。是预期的吗? appsettings.json 在文件夹中吗?

标签: azure asp.net-core azure-web-app-service .net-core asp.net-core-webapi


【解决方案1】:

在以后的 .net 核心版本中,使用 *.csproj 文件代替 project.json 文件。

您可以通过添加以下内容来修改文件以获得所需的结果:

   <ItemGroup>
      <Content Update="appsettings.json">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </Content>
   </ItemGroup>

【讨论】:

  • 在 Visual Studio 2019 中,通过解决方案资源管理器访问 appsettings.json 的属性窗格会生成 Include 而不是 Update.csproj 中:&lt;ItemGroup&gt; &lt;Content Include="appsettings.json"&gt; &lt;CopyToOutputDirectory&gt;PreserveNewest&lt;/CopyToOutputDirectory&gt; &lt;/Content&gt; &lt;/ItemGroup&gt;
  • 这就是答案!
【解决方案2】:

在我的情况下,文件appsettings.json 存在于项目文件夹中,但它被设置为Do not copy,我将设置更改为Copy always(见下图)。它对我有用。

它会自动将以下 XML 添加到您的 project.csproj 文件中:

<ItemGroup>
    <Content Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
</ItemGroup>

我看过其他答案,project.json 已死,正如answer 所说。

【讨论】:

  • 将“Build Action”设置为“Content”的目的是什么?如果将其设置为“无”,它似乎可以工作。
  • @JoePC 实际上在我的回答中我没有提到任何关于构建操作设置的事情,我不记得为什么我的设置当时设置为内容我做出了回答。有一个很好的答案涵盖了这部分,请查看stackoverflow.com/questions/145752/…
【解决方案3】:

在你的project.json

确保您已将 appsettings.json 包含为 copyToOutput

"buildOptions": {
   "emitEntryPoint": true,
   "preserveCompilationContext": true,
   "copyToOutput": {
     "include": [ "appsettings.json" ]
   }
 },

【讨论】:

  • 感谢您的评论。解决了我的问题。
【解决方案4】:

对我来说,错误是使用Directory.GetCurrentDirectory()。这在本地运行良好,但在生产服务器上,当程序从Powershell 启动时它失败了。替换为Assembly.GetEntryAssembly().Location,一切正常。

完整代码:

var builder = new ConfigurationBuilder()
        .SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
        .AddJsonFile("appsettings.json");

var configuration = builder.Build();

【讨论】:

  • 在.net5中,如果你设置&lt;PublishSingleFile&gt;true&lt;/PublishSingleFile&gt;,你会收到来自VS的警告,告诉你Assembly.GetEntryAssembly().Location总是空的。而是使用System.AppContext.BaseDirectory
  • +100。哦,伙计,你拯救了我的一天。这终于对我有用了。
【解决方案5】:

检查 project.json 中的 publishOptions 并确保“include”部分包含“appsettings.json”。 他们更改了 RTM 中的发布模型,要求您指定要从编译目录复制到 web 文件夹的所有内容。

编辑:请参阅下面的 Jensdc 答案,了解如何在 project.json 被杀死后使用 .csproj 执行此操作。

【讨论】:

  • 我认为您的意思是 appsettings.json,它不是 publishOptions 的一部分。我从一个工作项目中复制了一个 publishOptions:
  • 糟糕,是的 :) 当我在手机上接听电话时会发生这种情况 :)
【解决方案6】:

对我来说,解决的问题是设置在输出目录(构建目录)中包含appsettings.json 通过接口,如下所示:

【讨论】:

    【解决方案7】:

    您无需添加 .json 文件即可发布选项。 只是它在错误的路径中寻找文件。

    设置基本路径,然后添加json文件就可以了。

     public Startup(IHostingEnvironment environment)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(environment.ContentRootPath)
                .AddJsonFile("TestJson.json");
    
            Configuration = builder.Build();
        }
    

    这里,启动构造函数是使用 HostingEnviornment 构建的,并且基本路径设置为当前根路径。 它会起作用的!

    【讨论】:

      【解决方案8】:

      对我有用的是将appsettings.json 上的复制到输出目录属性更改为如果更新则复制

      【讨论】:

        【解决方案9】:

        我在从 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>
        

        【讨论】:

          【解决方案10】:

          此答案适用于...有人尝试在 VS Code 上进行调试,但 appsettings.json 没有被拾取。我尝试在 Visual Studio 中调试相同的解决方案,并且成功了。 此外,我能够访问环境变量。应用版本:Core 2.2。

          我删除了 .vscode 文件夹并再次调试,它成功了。

          【讨论】:

            【解决方案11】:

            对于我来说,我收到此错误是因为 JSON 文件语法错误(错字:删除的逗号)。

            默认情况下,appsettings.json 的属性“复制到输出目录”设置为“不复制”,我认为这是正确的。

            【讨论】:

              【解决方案12】:

              在使用 .net core 3 时遇到了同样的问题,这是有效的。

              <None Update="appsettings.json">
                  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
              </None>
              

              希望这很好

              【讨论】:

                猜你喜欢
                • 2021-07-25
                • 1970-01-01
                • 1970-01-01
                • 2017-08-21
                • 1970-01-01
                • 1970-01-01
                • 2016-12-28
                • 1970-01-01
                相关资源
                最近更新 更多