C# - AspNetCore设置内容根目录路径

4
我该如何在 .Net Core 3.0 ASP Blazor 应用程序中更改“内容根路径”?现在应用程序以输出方式启动。
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 path)C:\Windows\system32更改为其他路径。

如何在 AspNetCore 应用程序启动时更改内容根路径(Content root path)

4个回答

4
最正确的方法是修改项目的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>();
                });

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

1
请使用以下代码。
    public static async Task Main(string[] args)
    {
        string pathToContentRoot = string.Empty;

        var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
        pathToContentRoot = Path.GetDirectoryName(pathToExe);
        Directory.SetCurrentDirectory(pathToContentRoot);
    }

0

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

如果您启用了静态文件(UseStaticFiles)作为中间件, 您必须在某个地方也有这个设置。

           env.ContentRootPath = pathToContentRoot;

0

在 ASP7 中,我们插入了以下代码以使其在 program.cs 中工作。

WebApplicationOptions options = new WebApplicationOptions {
    ContentRootPath = "/var/www/yourpath"
};
var builder = WebApplication.CreateBuilder(options);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接