Ошибка configuration file was not found


Решение:

Выполнить два шага:

1) Перейти в папку :
SteamsteamappscommonBinary Domain

правая кнопка мыши на BinaryDomainConfiguration, свойства -> совместимость -> «Выполнять эту программу от имени администратора» -> нажать ok.

2) Запустить файл конфигурации -> «Audio Configuration» вкладка -> и изменить «Input Audio Adapter» на None, что означает микрофон, и нажать «Save and Quit». После этого игра запустится.

Enjoy :)

  • пожаловаться
  • скопировать ссылку


У меня так запустилась — нужно в папке с игрой steamapps / common/ binary domain найти BinaryDomainConfiguration и запустить его от имени администратора. Затем входим в аудио настройки и в Input audio выбираем none.

  • пожаловаться
  • скопировать ссылку


BeliySlon
Помогло ! Спасибо большое )

  • пожаловаться
  • скопировать ссылку


BeliySlon
ЧУВАК ТЫ ЛУЧШИЙ!ИЗМЕНИЛ ФОРМАТ ЗАПИСИ ЗВУКА В BinaryDomainConfiguration И ВСЕ ЗАРАБОТАЛО.
СПАСИБО ОГРОМНОЕ ЧУВАКИ!!!

  • пожаловаться
  • скопировать ссылку


dOrgnar
Вооо, а админы не хотят его добавить в Советы((( (Говорят уже не актуально)

  • пожаловаться
  • скопировать ссылку


zevsinc
Попробовал оба ваших метода — ничего не работает. Ни первый способ не второй.

  • пожаловаться
  • скопировать ссылку


zevsinc
Спасибо очень помогло

  • пожаловаться
  • скопировать ссылку


Botponevole, а ты не можешь скинуть?

  • пожаловаться
  • скопировать ссылку


Мне скинь пожалуйста))

  • пожаловаться
  • скопировать ссылку


Botponevole
Скинь)

  • пожаловаться
  • скопировать ссылку


Botponevole
мне если можно тоже скинь плз!!!!!

  • пожаловаться
  • скопировать ссылку


zevsinc
Человечише! Спасибо тебе!

  • пожаловаться
  • скопировать ссылку


народ а как найти папку Steam подскажите пожалуйста)

  • пожаловаться
  • скопировать ссылку


Похожая херня. Делаю все так же, но при нажатии «Save and Quit» зависает и ничего не происходит.
В заголовке окна пишет «Binary Domain Configuration (Не отвечает)»

  • пожаловаться
  • скопировать ссылку


zevsinc Привет всем. Сделал все что вы посоветовали но ничего в конфигурациях нет функцыи Save and Quit. Что в етом случае делать.

  • пожаловаться
  • скопировать ссылку


Читал,читал не чего не понял,я не качал её из стима просто пиратский репак,мне что посоветуете делать ошибка такая же Critical Error где эту папку искать хоть бы подсказали,в реестре или ещё где

  • пожаловаться
  • скопировать ссылку


cRUSis1989
Да не за что :)

  • пожаловаться
  • скопировать ссылку


zevsinc
Спасибо)))

  • пожаловаться
  • скопировать ссылку


И да,если у кого пропадет звук,ищите во вкладке Audio adapter/audio adapter свое звуковое устройство(в моем случае это было(Динамики(устройство с поддержкой High Definition Audio))

  • пожаловаться
  • скопировать ссылку


У меня вообще нет звука в игре=( Как исправить?

  • пожаловаться
  • скопировать ссылку


kBadratukВ конфигурации выбери настройки звука, а там Audio Adapter ставь на None

  • пожаловаться
  • скопировать ссылку


ЧУВАКИ ОБОЖАЮ ВАС ВЫ ТАК ПОМОГЛИ СПАСИБО ОГРОМНОЕ)))

  • пожаловаться
  • скопировать ссылку


попробуй готовый конфиг попросить у кого нибудь и закинуть в папку, где конфиги
: Steam / steamapps / common/ binary domain / savedata (конфиг)

  • пожаловаться
  • скопировать ссылку

Обновлено: 29.01.2023

Данная тема предназначена для решения технических проблем и вопросов связанных с игрой. Если вы хотите просто обсудить Binary Domain, то будьте добры, проследуйте по ссылке ниже в тему обсуждения.

В: Черные полосы по краям экрана. Как от них, таких некрасивых и назойливых, избавиться?
О: Запустите игру, пройдите по следующему адресу: «Options -> Screen -> Screen size» и там, путем перетаскивания ползунка, отрегулируйте размер полос на ваше усмотрение.

В: Как отдавать команды напарникам без микрофона, а то обижаются ведь, ироды!
О: В меню («Options -> Game settings») отключите голосовое управление (Voice input off). После этого все команды можно отдавать через кнопку Tab на клавиатуре.

В: Сильно сбоит управление в игре, несмотря на то что ручками выставлены все нужные значения в конфигураторе. Что делать?
О: Выдерните шнур, выдавите стекло. Или просто гляньте, не подключен ли к вашему ПК геймпад. Подключен? Отключите и наслаждайтесь.

В: Ай-яй, мою замечательную видеокарточку не видит конфигуратор игры, упорно замечая лишь интегрированную видеокарту. Что же делать мне посоветуете?
О: Ставьте бета-версию драйвера за номером 301.24 и будет вам щастье.

В: Мой англицкий игра криво воспринимать изволитъ. Можно её проучить, то есть научить меня понимайтъ?
О: Увы и ах, но нет. Выход один — использовать текстовые команды с клавиатуры (для них есть специальная кнопка, ага).

Эта публикация удалена, так как она нарушает рекомендации по поведению и контенту в Steam. Её можете видеть только вы. Если вы уверены, что публикацию удалили по ошибке, свяжитесь со службой поддержки Steam.

Этот предмет несовместим с Binary Domain. Пожалуйста, прочитайте справочную статью, почему этот предмет может не работать в Binary Domain.

Этот предмет виден только вам, администраторам и тем, кто будет отмечен как создатель.

В результатах поиска этот предмет сможете видеть только вы, ваши друзья и администраторы.

Configuration file not found please run the configuration tool

Configuration file not found please run the configuration tool fixing
Исправляем ошибку Configuration file not found please run the configuration tool возникающую при запуске игры

4

9,828 уникальных посетителей
73 добавили в избранное

Во вкладке Audio Adapter ставим Default
Во вкладке Input Audio Adapter ставим None

Select in Audio Adapter — Default
Select in Input Audio Adapter — None

правая кнопка мыши на BinaryDomainConfiguration, свойства -> совместимость -> «Выполнять эту программу от имени администратора» -> нажать ok.

2) Запустить файл конфигурации -> «Audio Configuration» вкладка -> и изменить «Input Audio Adapter» на None, что означает микрофон, и нажать «Save and Quit». После этого игра запустится.

ПРЕЖДЕ ЧЕМ ПОСТИТЬ В ТЕМЕ
РЕКОМЕНДУЕТСЯ ПОЧИТАТЬ ПРАВИЛА РАЗДЕЛА «GAMEZ BAZAR» и Правила форума

Binary Domain

Жанр: Action / TPS
Разработчик: SEGA
Издатель: SEGA
Платформы: PC , PS3 , Xbox 360
Дата выхода: уже в продаже

Данная тема предназначена для решения технических проблем и вопросов связанных с игрой. Если вы хотите просто обсудить Binary Domain, то будьте добры, проследуйте по ссылке ниже в тему обсуждения.

В: Черные полосы по краям экрана. Как от них, таких некрасивых и назойливых, избавиться?
О: Запустите игру, пройдите по следующему адресу: «Options -> Screen -> Screen size» и там, путем перетаскивания ползунка, отрегулируйте размер полос на ваше усмотрение.

В: Как отдавать команды напарникам без микрофона, а то обижаются ведь, ироды!
О: В меню («Options -> Game settings«) отключите голосовое управление (Voice input off). После этого все команды можно отдавать через кнопку Tab на клавиатуре.

В: Сильно сбоит управление в игре, несмотря на то что ручками выставлены все нужные значения в конфигураторе. Что делать?
О: Выдерните шнур, выдавите стекло. Или просто гляньте, не подключен ли к вашему ПК геймпад. Подключен? Отключите и наслаждайтесь.

В: Ай-яй, мою замечательную видеокарточку не видит конфигуратор игры, упорно замечая лишь интегрированную видеокарту. Что же делать мне посоветуете?
О: Ставьте бета-версию драйвера за номером 301.24 и будет вам щастье.

В: Мой англицкий игра криво воспринимать изволитъ. Можно её проучить, то есть научить меня понимайтъ?
О: Увы и ах, но нет. Выход один — использовать текстовые команды с клавиатуры (для них есть специальная кнопка, ага).

Читайте также:

  • Как сделать турель в реальной жизни
  • Rust как сделать ящик
  • Как нарисовать статую scp
  • Кодекс фавония genshin impact кому подходит
  • Dragon age inquisition хитрые демоны где видрис

The Azure error is:

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

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:

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

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.

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


    }
}

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.

Any ideas?

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

Edit2:
Per Frans, I checked the publishOptions. It was:

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

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

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

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"
    }
  },

And changed my startup to:

 services.AddDbContext<QuantaContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
        b => b.MigrationsAssembly("Quanta.API")));

Finally, it worked.

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

When you try to use the appsettings.json file in one project and set the startup project as another project. You will come across this error. Below is the complete error log.

Unhandled exception. System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:UsersuserOneDrive - jdbotsVisual StudioEFDemoConsoleAppbinDebugnetcoreapp3.1appsettings.json'.
   at Microsoft.Extensions.Configuration.FileConfigurationProvider.HandleException(ExceptionDispatchInfo info)
   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 DataAccessLayer.Models.EmployeeDBContext.OnConfiguring(DbContextOptionsBuilder optionsBuilder) in C:UsersuserOneDrive - jdbotsVisual StudioEFDemoDataAccessLayerModelsEmployeeDBContext.cs:line 29
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_Model()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.CheckState()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
   at DataAccessLayer.UserRepository.FetchEmployeeDetails(String empid) in C:UsersuserOneDrive - jdbotsVisual StudioEFDemoDataAccessLayerUserRepository.cs:line 21
   at ConsoleApp.Program.Main(String[] args) in C:UsersuserOneDrive - jdbotsVisual StudioEFDemoConsoleAppProgram.cs:line 12

The error stack might be somewhat different for you based on your implementation but the solution will be the same. Right-click on the appsettings.json file and click on Properties. This solution uses Visual Studio.

Check the property Copy to Output Directory. It might be Do not copy. Change this to Copy always.

Thank you All!!! Hope you find this useful.


You must log in to post a comment.

The Azure error is:

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

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:

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

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.

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


    }
}

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.

Any ideas?

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

Edit2:
Per Frans, I checked the publishOptions. It was:

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

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

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

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"
    }
  },

And changed my startup to:

 services.AddDbContext<QuantaContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
        b => b.MigrationsAssembly("Quanta.API")));

Finally, it worked.

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

Возможно, вам также будет интересно:

  • Ошибка configuration error 0x0002 configuration error 0x0003
  • Ошибка configuration error 0x0002 assassins creed 2
  • Ошибка config file cannot be loaded by unknown reason
  • Ошибка config 0x000001 знач буф 0x00 данн ис 0x02
  • Ошибка concrt140 dll что делать windows 10

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии