未找到配置文件“appsettings.json"且不是可选的 [英] The configuration file 'appsettings.json' was not found and is not optional

查看:42
本文介绍了未找到配置文件“appsettings.json"且不是可选的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Azure 错误是:

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

.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,但出现此错误:

So this is a bit vague. I can't seem to nail this down. I'm trying to deploy a .Net Core Web API project to Azure, and I'm getting this error:

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

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

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

I've deployed plain old .Net WebAPI's and they have worked. I've followed online tutorials and they have worked. But somehow my project is broke. Enabling stdoutLogEnabled on Web.config and looking at the Azure Streaming Logs gives me this:

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:SourceWorkspacesQuantasrcQuanta.APIStartup.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:homesitewwwroot
Now listening on: http://localhost:30261
Application started. Press Ctrl+C to shut down.

好的,这看起来很简单.它找不到 appsettings.json.查看我的配置( startup.cs ),它似乎定义得很好.我的 Startup 看起来像这样:

Ok, that seems simple. It can't find appsettings.json. Looking at my config ( startup.cs ) it seems very well defined. My Startup looks like this:

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 核心项目.但是,我将所有时间投入其中的这个项目似乎失败了.我正准备将无法运行的项目中的代码复制并粘贴到一个新项目中,但我真的很好奇这是什么问题.

This works fine locally. But once we publish to Azure, this fails. I'm at a loss. I've created new .Net core project that deploy to Azure just find. But this one project, that I put all my time into to, seems to fail. I'm about ready to copy and paste code out of the project that fails to run and into a new project, but i'm really curious on what's breaking this.

有什么想法吗?

所以我的 Program.cs 是:

So my Program.cs was:

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

根据 Frans,我检查了 publishOptions.那是:

Per Frans, I checked the publishOptions. It was:

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

我从一个工作项目中获取了一个 publishOptions 并将其更改为:

I took a publishOptions from a working project and changed it to:

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

它仍然给出 500 错误,但它没有给出堆栈跟踪说它可以加载 appsettings.json.现在它正在抱怨与 SQL 的连接.我注意到很多 RC1 博客文章中都提到了我的 SQL 连接字符串代码..Net Core 的 RC2 改变了它.所以我将其更新为:

It still gave a 500 error, but it didn't give a stack trace saying it coulding load appsettings.json. Now it was complaining about a connection to SQL. I noticed that my SQL connection string code is mentioned in a lot of RC1 blog posts. RC2 of .Net Core changed it. So I updated it to:

  "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 示例而没有意识到它.

I must have followed an older RC1 example and not realized it.

推荐答案

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

Check the publishOptions in project.json and make sure the "include" section has "appsettings.json" in it. They changed the publish model in RTM to require you to specify everything you want copied from the compile directory to the web folder.

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

See Jensdc answer below for how to do this with .csproj after project.json was killed.

这篇关于未找到配置文件“appsettings.json"且不是可选的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆