Почему для «Environment.CurrentDirectory» установлено значение «C: \\ Program Files \\ IIS Express»? - PullRequest
0 голосов
/ 12 января 2019

Я следую примеру шлюза API на https://www.c -sharpcorner.com / article / building-api-gateway-using-ocelot-in-asp-net-core /

И я создаю пустое веб-приложение asp.net и следую инструкциям, указанным в ссылке выше.

Функция My Main () в файле Program.cs:

    public static void Main(string[] args)
    {
        IWebHostBuilder builder = new WebHostBuilder();
        builder.ConfigureServices(s =>
        {
            s.AddSingleton(builder);
        });
        builder.UseKestrel()
               .UseContentRoot(Directory.GetCurrentDirectory())
               .UseStartup<Startup>()
               .UseUrls("http://localhost:9000");

        var host = builder.Build();
        host.Run();
    }

Кроме того, мой файл Startup.cs имеет следующий код:

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();
        builder.SetBasePath(Environment.CurrentDirectory)
               .AddJsonFile("configuration.json", optional: false, reloadOnChange: true)
               .AddEnvironmentVariables();

        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; private set; }

    // 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 https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        Action<ConfigurationBuilderCachePart> settings = (x) =>
        {
            x.WithMicrosoftLogging(log =>
            {
                log.AddConsole(LogLevel.Debug);

            }).WithDictionaryHandle();
        };
        services.AddOcelot();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        await app.UseOcelot();
    }
}

Когда я запускаю код, я получаю сообщение об ошибке для файла configuration.json NOT FOUND. И когда я проверяю исходный код текущего каталога в вышеприведенных функциях, я вижу, что Directory.GetCurrentDirectory() возвращает PATH как C:\\Program Files\\IIS Express, а не текущий каталог проекта.

У меня вопрос: почему указан путь к каталогу IIS? Как я могу это исправить?

Ответы [ 2 ]

0 голосов
/ 04 марта 2019

Вы также можете запустить это без процесса, пока не будет предоставлено постоянное исправление в .net core 3.0. Чтобы изменить это, вы можете изменить настройку в файле csproj с

<AspNetCoreHostingModel>inprocess</AspNetCoreHostingModel>

до

<AspNetCoreHostingModel>outofprocess</AspNetCoreHostingModel>

Или, если вы работаете в IISExpress, вы можете установить модель хостинга в файле launchsettings.json. Щелкните правой кнопкой мыши файл проекта в Visual Studion и выберите «Свойства» -> «Отладка» -> «Настройка веб-сервера» -> «Модель хостинга». Установка значения Out of Process добавит

"ancmHostingModel": "OutOfProcess" 

в профиль IIS Express в файле launchsettings.json

0 голосов
/ 12 января 2019

Это ошибка в ASP.NET Core 2.2 , о которой сообщалось в Github , и команда Microsoft ASP.NET Core предоставила следующее решение, и они добавят это решение. в функциональной версии ASP.NET Core.

Напишите вспомогательный класс следующим образом:

public class CurrentDirectoryHelpers
{
    internal const string AspNetCoreModuleDll = "aspnetcorev2_inprocess.dll";

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern IntPtr GetModuleHandle(string lpModuleName);

    [System.Runtime.InteropServices.DllImport(AspNetCoreModuleDll)]
    private static extern int http_get_application_properties(ref IISConfigurationData iiConfigData);

    [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
    private struct IISConfigurationData
    {
        public IntPtr pNativeApplication;
        [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)]
        public string pwzFullApplicationPath;
        [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)]
        public string pwzVirtualApplicationPath;
        public bool fWindowsAuthEnabled;
        public bool fBasicAuthEnabled;
        public bool fAnonymousAuthEnable;
    }

    public static void SetCurrentDirectory()
    {
        try
        {
            // Check if physical path was provided by ANCM
            var sitePhysicalPath = Environment.GetEnvironmentVariable("ASPNETCORE_IIS_PHYSICAL_PATH");
            if (string.IsNullOrEmpty(sitePhysicalPath))
            {
                // Skip if not running ANCM InProcess
                if (GetModuleHandle(AspNetCoreModuleDll) == IntPtr.Zero)
                {
                    return;
                }

                IISConfigurationData configurationData = default(IISConfigurationData);
                if (http_get_application_properties(ref configurationData) != 0)
                {
                    return;
                }

                sitePhysicalPath = configurationData.pwzFullApplicationPath;
            }

            Environment.CurrentDirectory = sitePhysicalPath;
        }
        catch
        {
            // ignore
        }
    }
}

Затем вызовите метод SetCurrentDirectory() в методе Main следующим образом:

public static void Main(string[] args)
{

     CurrentDirectoryHelpers.SetCurrentDirectory(); // call it here


    IWebHostBuilder builder = new WebHostBuilder();
    builder.ConfigureServices(s =>
    {
        s.AddSingleton(builder);
    });
    builder.UseKestrel()
           .UseContentRoot(Directory.GetCurrentDirectory())
           .UseStartup<Startup>()
           .UseUrls("http://localhost:9000");

    var host = builder.Build();
    host.Run();
}

Теперь все должно работать нормально!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...