8

푸른 오류는 다음과 같습니다구성 파일 'appsettings.json이'을 (를) 찾을 수 없습니다 및 선택하지되었다

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

그래서이 조금 모호합니다. 나는 이것을 내려 놓을 수 없다. 나는 푸른에 닷넷 코어 웹 API 프로젝트를 배포하기 위해 노력하고있어, 나는이 오류를 받고 있어요 :

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

나는 닷넷 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을 찾을 수 없습니다. 내 config (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가 : 당 프란스, 나는 publishOptions를 확인했습니다.

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

가},

내가 작업 프로젝트에서 publishOptions을 가져다

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

그것은 여전히 ​​500 오류를 준 :: 그것을 변경,하지만 포기하지 않았다 : 그것은이었다 스택 appsettings.json로드 coulding 말하는 스택 추적. 이제는 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에서 게시 모델을 변경했습니다.* .csproj 파일 대신 project.json 파일의 사용 project.json

가 나중에 .NET 코어 버전의 copyToOutput

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

나는 appsettings.json을 의미한다고 생각합니다. 그리고 그것은 publishOptions의 일부가 아닙니다. 내가 작업 프로젝트에서 publishOptions를 복사했습니다 : – Frank

+0

죄송합니다, 예 :) 그건 내 전화로 대답하면 어떻게됩니까 :) – Frans

22

.

당신은 추가하여 원하는 결과를 얻을 수있는 파일을 수정할 수 있습니다

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

의견을 보내 주셔서 감사합니다. 내 문제를 해결했다. –

20

으로 appsettings.json을 inlcuded입니다했는지 확인 당신에

3

당신은 옵션을 게시하여 .json 파일을 추가 할 필요가 없습니다. 잘못된 경로에서 파일을 찾는 것입니다.

기본 경로를 설정하고 json 파일을 추가하면 작동합니다.

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

     Configuration = builder.Build(); 
    } 

여기에서 시작 생성자는 HostingEnviornment로 빌드되고 기본 경로는 현재 루트 경로로 설정됩니다. 그리고 작동 할 것입니다!