【问题标题】:c# - AspNetCore set content root pathc# - AspNetCore 设置内容根路径
【发布时间】:2019-11-25 13:51:09
【问题描述】:

如何在应用程序 .Net Core 3.0 ASP Blazor 启动时更改 Content root path? 现在应用程序从输出开始

info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using 'C:\Users\Art\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
!!! C:\Program Files\WindowsApps\6c2bb0ad-5956-4886-9e3f-2135ebe50d2f_1.0.8.0_x64__n37t8n8dtxdg6\TUTDF_Viewer_v2\
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\Windows\system32

我需要在应用初始化时将 Content root pathC:\Windows\system32 更改为另一个路径。

如何在 AspNetCore 应用启动时更改Content root path

【问题讨论】:

    标签: c# asp.net asp.net-core blazor


    【解决方案1】:

    最正确的方法是改变项目的Program.cs——添加

    var p = System.Reflection.Assembly.GetEntryAssembly().Location;
                        p = p.Substring(0, p.LastIndexOf(@"\") + 1);
    webBuilder.UseContentRoot(p);
    

    CreateHostBuilder.

    完整示例:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        var p = System.Reflection.Assembly.GetEntryAssembly().Location;
                        p = p.Substring(0, p.LastIndexOf(@"\") + 1);
    
                        webBuilder.UseContentRoot(p);
                        webBuilder.UseStartup<Startup>();
                    });
    

    【讨论】:

    • 似乎不适用于 ASP.NET Core MVC v3.1 项目。我们的解决方案只是将当前目录更改为 webapp 目录并使用 dotnet 从那里启动 .dll
    【解决方案2】:

    请使用下面的代码

        public static async Task Main(string[] args)
        {
            string pathToContentRoot = string.Empty;
    
            var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
            pathToContentRoot = Path.GetDirectoryName(pathToExe);
            Directory.SetCurrentDirectory(pathToContentRoot);
        }
    

    【讨论】:

      【解决方案3】:

      Directory.SetCurrentDirectory 仅适用于加载 razor 内容和配置。

      如果您有静态文件 (UseStaticFiles) 作为活动中间件, 你一定也有这个地方。

                 env.ContentRootPath = pathToContentRoot;
      

      【讨论】:

        猜你喜欢
        • 2011-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多