找不到配置文件'appsettings.json',它不是可选的

时间:2016-08-26 03:14:52

标签: azure asp.net-core azure-web-sites .net-core asp.net-core-webapi

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)似乎很好定义。我的初创公司看起来像这样:

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();
        }
    }
}

EDIT2: 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示例而未实现它。

12 个答案:

答案 0 :(得分:42)

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

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

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

答案 1 :(得分:26)

project.json

确保您将appsettings.json作为copyToOutput

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

答案 2 :(得分:11)

检查project.json中的publishOptions并确保&#34; include&#34;部分有&#34; appsettings.json&#34;在里面。 他们在RTM中更改了发布模型,要求您指定要从编译目录复制到Web文件夹的所有内容。

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

答案 3 :(得分:10)

对我来说,解决的问题是设置为在输出目录(Build目录)中包含appsettings.json via interface ,如下所示:

enter image description here

答案 4 :(得分:9)

In My case the file appsettings.json in project folder, but it was not marked Do not copy, I changed the setting to Copy always (see images below). And it worked for me.

It will automatically added following XML to your project.csproj file:

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

I have looked at other answer, project.json is dead as this answer says.

enter image description here enter image description here

答案 5 :(得分:6)

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

设置基本路径,然后添加json文件,它将起作用。

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

        Configuration = builder.Build();
    }

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

答案 6 :(得分:3)

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

答案 7 :(得分:1)

此答案适用于...某人试图在VS Code上进行调试,但未获取appsettings.json。我尝试在Visual Studio中调试相同的解决方案,并且它起作用了。 另外,我能够访问环境变量。应用版本:Core 2.2。

我删除了.vscode文件夹,然后再次调试,就可以了。

答案 8 :(得分:0)

对我来说,由于Json文件语法错误(错字:已删除逗号),我遇到了此错误 默认情况下,appsettings.json的属性“复制到输出目录”设置为“请勿复制”,我认为这是正确的。

答案 9 :(得分:0)

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

完整代码:

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

var configuration = builder.Build();

答案 10 :(得分:0)

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

答案 11 :(得分:0)

使用.net core 3时遇到相同的问题,这是可行的。

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

希望这很好