8

Azureのエラーは次のとおりです。コンフィギュレーション・ファイル「appsettings.json」が見つかりませんし、オプションではありませんして

.Net Core: Application startup exception: System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional.

は、これは少しあいまいです。私はこれを釘付けにすることはできません。私はアズールには、.NETのコアのWeb APIプロジェクトを展開しようとしている、と私はこのエラーを取得しています:

:( Oops. 500 Internal Server Error An error occurred while starting the application.

私は、昔ながらの純WebAPIの者を展開してきましたし、彼らが働いています。私はオンラインチュートリアルに続き、彼らは働いてきました。しかし、どういうわけか私のプロジェクトは壊れています。簡単なようで[OK]を

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. 

、:Web.configファイルにstdoutLogEnabledを有効にすると、Azureのストリーミングのログを見ていると、私は、この与えます。 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コアプロジェクトを作成しました。しかし、この1つのプロジェクトは、すべて私の時間を忘れてしまったようです。私は、実行に失敗したプロジェクトから新しいプロジェクトにコードをコピー&ペーストする準備ができていますが、これを壊していることに本当に興味があります。

アイデア?

EDIT: だから私の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: 毎のFransは、私がpublishOptionsをチェックします。それがあった:

"publishOptions": { 
"include": [ 
    "wwwroot", 
    "web.config" 
] 

}、

は、私はそれはまだ500エラーを与えたが、それは与えていない作業プロジェクトからpublishOptionsを取り、

"publishOptions": { 
    "include": [ 
    "wwwroot", 
    "Views", 
    "Areas/**/Views", 
    "appsettings.json", 
    "web.config" 
    ] 
    }, 

::のためにそれを変更しましたload appsettings.jsonという名前のスタックトレース。今は、SQLへの接続について不平を言っていました。私は、私のSQL接続文字列コードがRC1のブログ記事の多くに記述されていることに気付きました。 .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の例に従っていて、わかりません。

+0

エラーメッセージに「コンテンツルートパス:D:\ home \ site \ wwwroot」があります。それは期待されていますか? 'appsettings.json'はフォルダにありますか? –

答えて

7

project.jsonのpublishOptionsを確認し、「include」セクションに「appsettings.json」が含まれていることを確認してください。 RTMのパブリッシュモデルを変更して、コンパイルディレクトリからWebフォルダにコピーするすべてのものを指定する必要がありました。あなたのproject.json

+0

私はあなたがappsettings.jsonを意味すると思う、それはpublishOptionsの一部ではありませんでした。 – Frank

+0

私は自分の電話で答えたらどうなるのですか? – Frans

22

あなたは* .csprojファイルが代わりにproject.jsonファイルを使用した後に、.NETコアバージョンでcopyToOutput

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

あなたのコメントありがとうございます。私の問題を解決しました。 –

20

としてappsettings.jsonをinlcudedていることを確認。

あなたは追加することによって、望ましい結果を得るためにファイルを変更することができます

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

あなたはオプションを公開するためにあなたの.jsonファイルを追加する必要はありません。 間違ったパスでファイルを探しているだけです。

ベースパスを設定し、jsonファイルを追加すると動作します。

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

     Configuration = builder.Build(); 
    } 

ここで、スタートアップコンストラクタはHostingEnviornmentで構築され、ベースパスは現在のルートパスに設定されています。 それは動作します!

関連する問題