簡體   English   中英

asp.net 核心不加載靜態文件

[英]asp.net core not loading static files

我有一個帶有以下代碼的應用程序 .NET core 2.1:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseStaticFiles();
        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "Assets")),
            RequestPath = "/Assets"
        });
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
    }

和我的結構文件夾:

在此處輸入圖片說明

但這些網址都沒有打開圖像:

“my-website.com/images/snes/alien.jpg”

“my-website.com/wwwroot/images/snes/alien.jpg”

“my-website.com/Assets/Snes/alien.jpg”

有人知道出了什么問題嗎?

編輯:這是 CurrentDirectoy() 方法獲取的文件夾(顯然是正確的):

在此處輸入圖片說明

Edit2:使用此代碼在 localhost 上工作,但在我在 azure 上發布時卻沒有:

 app.UseFileServer(
        new FileServerOptions()
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"))
        });

您所在的工作目錄很可能與您想象的不同。 請通過在 foo 上設置斷點來檢查這一點:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    var foo = Directory.GetCurrentDirectory();
}

解決方案取決於您如何啟動應用程序。

如果您通過 Visual Studio 執行此操作,您可能在項目屬性中設置了另一個工作目錄?

項目屬性

如果通過命令行,您需要cd到您的項目根目錄。

另一種解決方案是使用程序集目錄

// get the directory
var assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
var assetDirectory = Path.Combine(assemblyDirectory, "Assets"));

// use it
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(assetDirectory),
    RequestPath = "/Assets"
});

如果你使用的是可視化代碼,那么你必須在你的lunch.json文件的configuration數組的cwd參數中設置你的工作目錄。 見附件截圖。

在此處輸入圖片說明

使用IHostingEnvironment

app.UseStaticFiles(new StaticFileOptions
{
     FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Assets")),
            RequestPath = "/Assets"
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM